Taking a string in one language and converting it into a string in another is sometimes annoying. One that is annoying, but yet possible, is converting a PHP string of maybe a web page or maybe an error message or whatever, and passing the string through to JavaScript to be manipulated in some way or another.

function QuoteForJavaScript($str, $SkipQuotes = false) {
    $R = array("/(<scr)(ipt)/i" => "$1\"+\"$2",  // Break up "<script" tags
	       '/\\\\/' => '\\\\',               // Escape backslashes
	       '/"/' => '\\"',                   // Escape quotes
	       '/\'/' => '\\\'',                 // Escape single quotes
	       "/\r\n/" => "\n",                 // Convert DOS newlines into Unix
	       "/\r/" => "\n",                   // Convert Mac newlines into Unix
	       "/\n/" => "\\n\"+\n\"");          // Convert Unix newlines
    $str = preg_replace(array_keys($R), array_values($R), $str);
    if (! $SkipQuotes)
      return '"' . $str . '"';
    return $str;

To use this glorious function, you need to merely pass it a string and optionally use the $SkipQuotes parameter. Here are a few examples of PHP writing some JavaScript.

$str = "12345 abcde";
echo "js_var = " . QuoteForJavaScript($str) . ";\n";

// Produces:
// js_var = "12345 abcde";

$str = "It's a \"quoted\" thing!\nAnd a backslash \ on a second line!";
echo "js_var = " . QuoteForJavaScript($str) . ";\n";

// This result is a bit more interesting:
// js_var = "It\'s a \"quoted\" thing!\n" +
// "And a backslash \\ on a second line!";
// Everything is escaped properly, the newline is preserved, and the string
// splits on the newline for readability.

// If you need to use it in the middle of some other JavaScript, you can
// turn off the addition of the outer double quotes.

// Leave PHP code and go to the HTML (which should be in the middle of 
// a >script< tag...
js_var = "This is string number <?= QuoteForJavaScript(1234, true) ?>";
// Return to PHP to complete the example

// That produces this following line, without the extra quotes around
// the number.
// js_var = "This is string number 1234";

Have fun using this function! Just keep in mind that it isn't designed for binary data. Well, for that matter, JavaScript really isn't either.

The most popular toy in 1867 was Parcheesi. Tyler Akins! <>
Contact Me - Legal Info