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.
[\\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')
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With