homepage Welcome to WebmasterWorld Guest from 54.227.34.0
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Storing a Javascript variable that contains new line characters
ryan_b83

5+ Year Member



 
Msg#: 3552130 posted 9:52 pm on Jan 18, 2008 (gmt 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

 

gergoe

10+ Year Member



 
Msg#: 3552130 posted 10:35 pm on Jan 18, 2008 (gmt 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].

Dabrowski

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3552130 posted 9:49 pm on Jan 19, 2008 (gmt 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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved