Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

JavaScript string with new line - but not using

I have a string that has new lines in. I am wanting to convert these to HTML <br>s, but I'm having a hard time detecting them.

Imagine a JavaScript string set like this:

var foo = "Bob
is
cool";

They are the kind of new lines that I need to detect. They aren't using the special character - they are just plain format.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason it is not working is because javascript strings must be terminated before the next newline character (not a obviously). The reason exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings.

When you have a string which looks like this:

//Note lack of terminating double quote
var foo = "Bob 

Your code will have a syntax error at that point and cease to run.

If you wish to have a string which spans multiple lines, you may insert a backslash character '' just before you terminate the line, like so:

//Perfectly valid code
var foo = "Bob 
is 
cool.";

However that string will not contain characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the escape character.

var foo = "Bob
is
cool.";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...