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 \n special character – they are just plain format.
The reason it is not working is because javascript strings must be terminated before the next newline character (not a
\nobviously). The reason\nexists 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:
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:However that string will not contain
\ncharacters 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\nescape character.