带有新行的 JavaScript 字符串 - 但不使用 \n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10154429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:05:30  来源:igfitidea点击:

JavaScript string with new line - but not using \n

javascriptstring

提问by Randy the Dev

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.

我有一个包含新行的字符串。我想将这些转换为 HTML <br>s,但我很难检测到它们。

Imagine a JavaScript string set like this:

想象一个这样的 JavaScript 字符串集:

var foo = "Bob
is
cool";

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

它们是我需要检测的那种新行。他们没有使用\n特殊字符 - 它们只是普通格式。

回答by Randy the Dev

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.

它不起作用的原因是因为 javascript 字符串必须在下一个换行符之前终止(不是很\n明显)。\n存在的原因是让开发人员可以轻松地将换行符(ASCII:10)放入他们的字符串中。

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 notcontain \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.

但是,该字符串将不会\n在字符串被分成单独行的位置包含字符。在字符串中插入换行符的唯一方法是插入值为 10 的字符,最简单的方法是\n转义字符。

var foo = "Bob\nis\ncool.";

回答by David Refoua

UPDATE:I just came acrossa wonderful syntax design in JavaScript-ES6 called Template literals. What you want to do can be literally be done using `(backtick or grave accent character).

更新:我刚刚在 JavaScript-ES6 中遇到了一个很棒的语法设计,称为Template literals。您可以使用`(反引号或重音符号)字面上完成您想要做的事情。

var foo = `Bob
is
cool`;

In which case, foo === "Bob\nis\ncool"is true.

在这种情况下,foo === "Bob\nis\ncool"是真的。

Why the designers decided that ` ... `can be left unterminated, but the " ... "and ' ... 'are illegal to have newline characters in them is beyond me.

为什么设计者决定` ... `可以留下未终结,但" ... "' ... '是非法的换行符在他们超越我。

Just be sure that the targeting browser supports ES6-specified Javascript implementation.

请确保目标浏览器支持 ES6 指定的 Javascript 实现。

 

 



P. S. This syntax has a pretty cool feature that is similar to PHP and many more scripting languages, namely "Tagged template literals" in which you can have a string like this:

PS 这个语法有一个很酷的特性,类似于 PHP 和更多的脚本语言,即“标记模板文字”,你可以在其中使用这样的字符串:

var a = 'Hello', b = 'World';
console.log(`The computer says ${ a.toUpperCase() }, ${b}!`);
// Prints "The computer says HELLO, World!"

回答by cfedermann

Check for \nor \ror \r\n.

检查\n\r\r\n

There are several representations of newlines, see http://en.wikipedia.org/wiki/Newline#Representations

有几种换行表示,请参阅http://en.wikipedia.org/wiki/Newline#Representations

回答by Evert

I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.

我认为您不了解 \n 的工作原理。结果字符串仍然只包含一个值为 10 的字节。这在 javascript 源代码中用 \n 表示。

The code snippet you posted doesn't actually work, but if it did, the newline wouldbe equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).

您发布的代码片段实际上不起作用,但如果确实有效,则换行符等效于 \n,除非它是 Windows 样式的换行符,在这种情况下它将是 \r\n。(但即使替换仍然有效)。

回答by Yaron U.

you can use the following function:

您可以使用以下功能:

  function nl2br (str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '' + breakTag + '');
  } 

like so:

像这样:

var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);

this should alert line<br>another line<br>another line

这应该提醒 line<br>another line<br>another line

the source of the function is from here: http://phpjs.org/functions/nl2br:480

该函数的来源来自这里:http: //phpjs.org/functions/nl2br: 480

this imitates the nl2brfunction in php...

这是模仿nl2brphp中的函数...

回答by J.T. Houtenbos

This is a small adition to @Andrew Dunn's post above

这是上面@Andrew Dunn 帖子的一个小补充

Combining the 2 is possible to generate readable JS and matching output

结合 2 可以生成可读的 JS 和匹配的输出

 var foo = "Bob\n\
    is\n\
    cool.\n\";

回答by Simon Edstr?m

I think they using \nanyway even couse it not visible, or maybe they using \r. So just replace \nor \rwith <br/>

我认为他们\n无论如何都使用它甚至不可见,或者他们使用\r. 所以只需替换\n\r使用<br/>

回答by Dikshit Kathuria

The query string that I used to to escape the new line character in JS : LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;

我用来在 JS 中转义换行符的查询字符串: LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;

This involves new ES6 syntax - Template Literals `` and I tried changing '\n' to '\r\n' and worked perfectly in my case.

这涉及到新的 ES6 语法 - Template Literals `` 并且我尝试将 '\n' 更改为 '\r\n' 并且在我的情况下完美地工作。

PS: This example is my query to upload CSV data into mysql DB.

PS:此示例是我将 CSV 数据上传到 mysql DB 的查询。