Welcome to WebmasterWorld Guest from

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)

5+ Year Member

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?



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

10+ Year Member

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)

WebmasterWorld Senior Member 5+ Year Member

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... 

## To change linebreaks into actual linebreak escapes...

You could also use this for other escape characters.


Featured Threads

Hot Threads This Week

Hot Threads This Month