在javascript字符串中写双引号
我正在使用一种方法在字符串中迭代执行替换。在javascript字符串中写双引号
function replaceAll(srcString, target, newContent){
while (srcString.indexOf(target) != -1)
srcString = srcString.replace(target,newContent);
return srcString;
}
但它不适合我想要的目标文本工作,主要是因为我想不出如何正确地写文字:我想删除就是,从字面上看,"\n"
,(包括逗号和引号),那么通过第二个参数才能使其正常工作?
在此先感谢。
你需要逃避的报价,如果使用双引号的第一个参数replace
'some text "\n", more text'.replace("\"\n\",", 'new content');
,或者你可以在第二个例子中做
'some text "\n", more text'.replace('"\n",', 'new content');
注,替换的第一个参数使用单引号来表示字符串,因此您不需要转义双引号。
最后,还有一个选项是在上月底replace
调用
'some text "\n", more text "\n",'.replace(/"\n",/g, 'new content');
的“G”使用正则表达式使得更换更换,所有(全局)。
+1(但用单引号不需要跳过双引号......) – 2012-08-07 13:07:56
@RobI thanx,在我的回答中加入 – hvgotcodes 2012-08-07 13:09:18
另外,要指定'/ g'选项来匹配所有出现的内容。 – Austin 2012-08-07 13:15:36
要删除"\n"
,只需使用String.replace
:
srcString.replace(/"\n"[,]/g, "")
您可以替换使用正则表达式/"\n"[,]/g
用户询问删除报价以及... – 2012-08-07 13:07:24
答案已更新 – Austin 2012-08-07 13:14:14
没有必要对这样的功能。替换函数有一个额外的参数g
,它取代所有出现的不是第一个:
'sometext\nanothertext'.replace(/\n/g,'');
不管字符串中的报价是否被转义与否:
var str = 'This string has a "\n", quoted newline.';
或
var str = "This string has a \"\n\", escaped quoted newline.";
解决方案是相同的(将'!!!'更改为您要替换的内容"\n",
:
str.replace(/"\n",/g,'!!!');
这是可怕的效率低下,没有必要的,因为你可以使用正则表达式与全球标志。 – Esailija 2012-08-07 13:12:47