Reputation: 3024
I have a series of data that I want to put inside an array in a javascript. I use Wordpress as a cms, and my data looks like this (the content of the post):
line1
line2
line3
However when i try to seek data from the post I see this code in javascript for let's say 3 posts:
var locations=['line1
line2
line3','line1
line2
line3','line1
line2
line3'];
I receive this error when I look in the console: Uncaught SyntaxError: Unexpected token ILLEGAL. I have searched here a lot of answers but I did not succeed into breaking a leg with it. However I had a look in the HTML tab of the content there is no <br/>
, so the new line is not html code.
I also tried to escape special characters in php like this, but it pops out the same error:
echo '\''.htmlspecialchars (get_the_content()).'\',';
However, if the content is in one line, like 'some text' it appears to run ok.
Any ideas?
Thank you!
Upvotes: 0
Views: 176
Reputation: 798536
Use json_encode() to turn it into a JavaScript literal before outputting it.
Upvotes: 2
Reputation: 14304
Actually this is a php question. Javascript have no way to "recover" from such syntax errors by itself.
echo "'".str_replace(
array("'", "\n", "\r"),
array("\\'", "\\n", "\\r"),
get_the_content()
)."'";
Upvotes: 1