简体   繁体   中英

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.

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?

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/

Javascript does not have multi-line variables like php does, unless you manually escape( \\ ) the end of the line. Further, this does not count as a line-break, so you would have to insert \\n s to fix that as well. 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. 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, ',');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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