Nick Deny Nick Deny - 4 months ago 27
Javascript Question

Javascript | Can't replace \n with String.replace()

I have code which parse web-site and take information from database.
It's look like this:

var find = body.match(/\"text\":\"(.*?)\",\"date\"/);

As result, I have:

гороскоп на июль скорпион\nштукатурка на газобетон\nподработка на день\nмицубиси тюмень\nсокращение микрорайон

Then i try to replace \n, but it's don't working.

var str = find[1].replace(new RegExp("\\n",'g'),"*");

What I can do with this?


It looks like you want to replace the text \n, i.e. a backslash followed by an n, as opposed to a newline character.

In which case you can try

var str = find[1].replace(/\\n/g, "*");

or the less readable version

var str = find[1].replace(new RegExp("\\\\n", "g"), "*");

In regular expressions, the string \n matches a newline character. To match a backslash character we need to 'escape' it, by preceding it with another backslash. \\ in a regular expression matches a \ character. Similarly, in JavaScript string literals, \ is the escape character, so we need to escape both backslashes in the regular expression again when we write new RegExp("\\\\n", "g").