Search the blog

Sometimes you may have a string that you wish to output either as a JavaScript string or within a JavaScript string.

Like PHP, JavaScript allows you to use either single or double quotes so this will need to be considered. Another consideration is that JavaScript doesn’t allow unescaped new lines in strings; there are also other special characters to consider.

Thankfully, the json_encode function found in PHP sorts all this out for us. The (potential) issue is, however, JSON only uses double quotes and always returns a complete string, i.e. double-quotes at either end. So, here’s a simple function that allows you to convert PHP strings for use as JavaScript strings according to your preference.

Note that, depending on the context you may need to call htmlspecialchars on the string before sending it to the function.

<?php

function formatJavaScript($string, $doubleQuotesContext = true, $addQuotes = false) {

    // It must be a string else numbers get mangled
    $string = (string) $string;
        
    // Encode as standard JSON, double quotes
    $string = json_encode($string);
        
    // Remove " from start and end"
    $string = mb_substr($string, 1, -1);
    
    // If using single quotes, reaplce " with ' and escape
    if ($doubleQuotesContext === false) {
        
        // Remove \ from "
        $string = str_replace('\"', '"', $string);
            
        // Escape single quotes
        $string = str_replace("'", "\'", $string);
        
    }
        
    if ($addQuotes === true) {
    
        if ($doubleQuotesContext === true) {
        
            $string = '"' . $string . '"';
        
        } else {
        
            $string = "'" . $string . "'";
            
        }
    
    }
        
    return $string;
        
}

$string = 'This is
"a"

	\'test string\'';

echo '<pre>';
echo formatJavaScript($string) . "\n"; // For use within double-quoted JavaScript string
echo formatJavaScript($string, false) . "\n"; // For use within single-quoted JavaScript string
echo formatJavaScript($string, false, true) . "\n"; // A complete double-quoted JavaScript string
echo formatJavaScript($string, true, true) . "\n"; // A complete single-quoted JavaScript string
echo '</pre>';
echo formatJavaScript(htmlspecialchars($string, ENT_QUOTES)) . "\n"; // Escaped output

?>

It should output:

This is\n\"a\"\n\n\t'test string'
This is\n"a"\n\n\t\'test string\'
'This is\n"a"\n\n\t\'test string\''
"This is\n\"a\"\n\n\t'test string'"

This is\n"a"\n\n\t'test string'

Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.