Welcome to WebmasterWorld Guest from 107.20.110.201

Forum Moderators: open

Message Too Old, No Replies

Storing a Javascript variable that contains new line characters

     

ryan_b83

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?

Thanks,
Ryan

gergoe

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

Dabrowski

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... 
s/\r//g;

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

You could also use this for other escape characters.

 

Featured Threads

Hot Threads This Week

Hot Threads This Month