Javascript |无法将\ n替换为String.replace() [英] Javascript | Can't replace \n with String.replace()

查看:472
本文介绍了Javascript |无法将\ n替换为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\"/);

结果,我有:

然后我尝试替换\ n,但是它不起作用.

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

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

我可以做什么?

推荐答案

您似乎想要替换文本\n,即反斜杠后跟n,而不是换行符.

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, "*");

或可读性较低的版本

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

在正则表达式中,字符串\n与换行符匹配.要匹配反斜杠字符,我们需要在其前面加上另一个反斜杠来对其进行转义".正则表达式中的\\\字符匹配.同样,在JavaScript字符串文字中,\是转义字符,因此我们在编写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").

这篇关于Javascript |无法将\ n替换为String.replace()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆