带有换行符的JavaScript字符串 - 但不使用\ n [英] JavaScript string with new line - but not using \n
问题描述
我有一个包含新行的字符串。我想将它们转换为HTML < br>
s,但我很难检测到它们。
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.
想象一下这样设置的JavaScript字符串:
Imagine a JavaScript string set like this:
var foo = "Bob
is
cool";
它们是我需要检测的那种新行。他们没有使用 \ n
特殊字符 - 它们只是普通格式。
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.
推荐答案
它不起作用的原因是因为javascript字符串必须在下一个换行符之前终止(显然不是 \ n
)。 \ n
存在的原因是允许开发人员轻松地将换行符(ASCII:10)放入其字符串中。
The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n
obviously). The reason \n
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.";
然而该字符串将 包含 \ n
字符串被分成不同行的位置。将换行符插入字符串的唯一方法是插入一个字符串值为10的字符,最简单的方法是 \ n
转义字符。
However that string will not contain \n
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 \n
escape character.
var foo = "Bob\nis\ncool.";
这篇关于带有换行符的JavaScript字符串 - 但不使用\ n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!