最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Javascript | Can't replace n with String.replace() - Stack Overflow

programmeradmin7浏览0评论

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?

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?

Share Improve this question asked Oct 2, 2016 at 19:40 Nick DenyNick Deny 1271 gold badge1 silver badge10 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

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

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.

removes all 3 types of line breaks

let s = find[1].replace(/(\r\n|\n|\r)/gm, " - ")

发布评论

评论列表(0)

  1. 暂无评论