The King is The King is - 1 year ago 80
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 Source

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


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

Feature         Chrome  Edge    Firefox (Gecko) Internet Explorer   Opera   Safari
Basic support   41      (Yes)   34 (34)         No support          28      9
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download