Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace newline escape sequence with newline

Tags:

javascript

I'm looking to replace any occurrences of the string "\n" with the new line character: '\n'.

replace(/[\\n]/g, "\n") doesn't seem to work.

I'm unfamiliar with regex and was wondering if someone could help.

like image 617
dk123 Avatar asked Jul 28 '14 05:07

dk123


2 Answers

[\\n] is the set of the characters \ and n. Just take off the brackets:

….replace(/\\n/g, '\n')

In modern JavaScript environments, you can use String.prototype.replaceAll (ES2021) instead:

….replaceAll('\\n', '\n')
like image 100
2 revs Avatar answered Nov 18 '22 21:11

2 revs


Don't abuse regex!

If you are testing for single strings, test for single strings.

Since JavaScript doesn't have a built in replaceAll method (yet) for strings, you can make your own:

String.prototype.replaceAll = function(find, replace) {
    return this.split(find).join(replace);
};

Then just call it like this:

mystring.replaceAll('\\n', '\n'); // for the "find" argument, you need to escape the backslash

Of course, if you don't like fiddling with the prototype (there are reasons to, and not to - decide yourself), you can define it as a regular function:

function replaceAll(string, find, replace) {
    return string.split(find).join(replace);
}

Then call it like this:

replaceAll(mystring, '\\n', '\n');
like image 26
bjb568 Avatar answered Nov 18 '22 21:11

bjb568