I am trying to replace line breaks with a ma 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 / Anyone know how to fix it?
I am trying to replace line breaks with a ma 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/CBvpS/ Anyone know how to fix it?
Share Improve this question asked Jan 12, 2013 at 0:53 RurikoRuriko 1791 gold badge6 silver badges12 bronze badges 1- 3 Well, for starters, javascript does not have multi-line variables, unless the end is escaped. – Daedalus Commented Jan 12, 2013 at 0:54
3 Answers
Reset to default 4Works 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/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, ',');