Javascript | Can't replace \n with String.repl

2019-05-28 19:02发布

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?

2条回答
ら.Afraid
2楼-- · 2019-05-28 19:17

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").

查看更多
疯言疯语
3楼-- · 2019-05-28 19:28

Working in the console!

Here this works globally and works on both types of line breaks:

find[1].replace(/\r?\n/g, "*")

if you dont want the '\r' to be replaced you could simply remove that from the regex.

查看更多
登录 后发表回答