The King is The King is - 3 months ago 9
jQuery Question

How to escape line breaks using jQuery

I have a value extracted from my database table which contains characters like

"
'
<
>
and line breaks also, now I want to pass it to a jQuery variable like this

var str = "<?php echo $str; ?>";


But I always get an error in my console.log because of these characters and the line breaks. Please how can I fix this using jQuery?

Answer

Multiline strings are not supported by most browsers. Therefore, you probably need to fix the string in your PHP.

If you are targeting new browser versions, you can try to use backticks:

var str = ` This is a 
multiline string supporting brackets, quotes and single quotes:

" " "

' ' '

<> {} ()

` // only the backtick will end the string

console.log(str);


As you can see on MDN, the browser support is pretty minimal though.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Feature         Chrome  Edge    Firefox (Gecko) Internet Explorer   Opera   Safari
Basic support   41      (Yes)   34 (34)         No support          28      9