Welcome to WebmasterWorld Guest from 54.159.50.111

Forum Moderators: open

Message Too Old, No Replies

Storing a Javascript variable that contains new line characters

     
9:52 pm on Jan 18, 2008 (gmt 0)

Junior Member

5+ Year Member

joined:July 28, 2006
posts: 168
votes: 0


Hello, I am having syntax errors in JavaScript. Its pretty basic and hoping someone has a quick solution. I am by no means a JavaScript guru...lol

Basically I am pulling a large string from a database for example:

"This is my string I am getting from the database

It also contains new line characters"

So when I assign this string to a JavaScript variable I get a syntax error because the JavaScript variables do not allow for new line characters.

Any Ideas?

Thanks,
Ryan

10:35 pm on Jan 18, 2008 (gmt 0)

Preferred Member

10+ Year Member

joined:May 4, 2004
posts:525
votes: 0


Javascript is strict in this manner, a string must consist only one line in the source code. To get around this, you only need to replace newline characters before sending them to the browser in your string to \n (escaped newline character). For example the alert("Hello\nWorld!"); would print "Hello" and "World!" in a new line.

See the list of (other) escape sequences [javascriptkit.com].

9:49 pm on Jan 19, 2008 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:Mar 29, 2007
posts:1147
votes: 0


Ryan, what language are you using to get the data from the database and write the JS?

If you are in Perl you can easily fix this with a couple of regex's...

## To remove UNIX/MAC newline charaters... 
s/\r//g;

## To change linebreaks into actual linebreak escapes...
s/\n/\\n/g;

You could also use this for other escape characters.