1

I have a text which was retrieved from my database with PHP and has characters like " ' and also has line breaks. Now I passed it to a jQuery string using the backticks like this

var str = `<?php echo $text; ?>`;

And it works fine with desktop browsers but when I try it with mobile browsers though I can't see the console.log in mobile browsers but I believe I am getting some errors because my jQuery code refuse to function, but when I comment out the above line it works fine. Please anyone know how I can fix this?

  • That's a [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), which is a newer kind of string literal. They are new to ES6, which means they aren't supported in some browsers. – 4castle Sep 12 '16 at 16:36

1 Answers1

4

You're relying on a fairly new feature of JavaScript (officially introduced in June 2015 as part of ES2015, aka "ES6"): Template literals. It's not surprising you're running into browsers with older JavaScript engines that don't support template literals.

It would also fail if the output happened to contain backticks.

The correct thing to do here is properly escape the string content. PHP's json_encode will happily take a string and output a JavaScript-compatible, escaped version for you:

var str = <?php echo json_encode($text); ?>;

If $text contains a string, for instance:

Bob: Hi, my name is Bob, but people call me "Bobby;" it's a nickname.
Wilma: Hi Bobby!

what would arrive at the browser would be:

var str = "Bob: Hi, my name is Bob, but people call me \"Bobby;\" it's a nickname.\nWilma: Hi Bobby!";
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875