简体   繁体   English

如何更换换行符?

[英]How do I replace line breaks?

I am trying to replace line breaks with a comma in javascript but the code doesn't seem to work. 我正在尝试用javascript中的逗号替换换行符,但是代码似乎无法正常工作。

var data = "Series
Manga
Games
Artbooks
Visual Novels"
var output = data.replace(/(\r\n|\n|\r)/gm,",");
alert(output);

here you can see a online version http://jsfiddle.net/CBvpS/ Anyone know how to fix it? 在这里您可以看到在线版本http://jsfiddle.net/CBvpS/任何人都知道如何解决它?

Works great when your input string is syntactically correct: 当输入字符串在语法上正确时,效果很好:

var data = "Series\nManga\nGames\nArtbooks\nVisual Novels"
var output = data.replace(/\r?\n/gm,",");
alert(output);

http://jsfiddle.net/7V8rg/1/ http://jsfiddle.net/7V8rg/1/

Javascript does not have multi-line variables like php does, unless you manually escape( \\ ) the end of the line. Javascript不像php一样具有多行变量,除非您手动对行尾进行转义( \\ )。 Further, this does not count as a line-break, so you would have to insert \\n s to fix that as well. 此外,这不算作换行符,因此您还必须插入\\n来解决该问题。 Otherwise, your code works fine , albeit with some minor modifications. 否则, 您的代码可以正常运行 ,尽管进行了一些小的修改。

var data = "Series\n \
Manga\n \
Games\n \
Artbooks\n \
Visual Novels";
var output = data.replace(/(\r\n|\n|\r)/gm,",");
alert(output);

Take note, however, if your data is from example, an input text area, you do of course not need to worry about escaping the end of the line, and it will handle the data as it should. 但是请注意,如果您的数据来自示例输入文本区域,那么您当然不必担心转义行尾,它将按需处理数据。

JavaScript doesn't allow you to continue a string with new lines unless you add a backslash at the end of the line. JavaScript不允许您用新行继续字符串,除非您在行末添加反斜杠。 For example: 例如:

var string = "a \
string is \
here";

With that being said, if you retrieved some text from a different source and wanted to replace the new lines, something like this should be all you need: 话虽如此,如果您从其他来源检索到一些文本并希望替换新行,则只需要这样的内容:

string = string.replace(/\n/g, ',');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM