简体   繁体   English

用JavaScript字符串写双引号

[英]Writing double quotes in javascript string

I'm using a method to iteratively perform a replace in a string. 我正在使用一种方法来迭代执行字符串中的替换。

function replaceAll(srcString, target, newContent){
  while (srcString.indexOf(target) != -1)
  srcString = srcString.replace(target,newContent);
  return srcString;
}

But it doesn't work for the target text that I want, mainly because I can't think of how to properly write that text: What I want to remove is, literally, "\\n" , (included the comma and the quotes), so what to pass as second param in order to make it work properly? 但这不适用于我想要的目标文本,主要是因为我无法考虑如何正确编写该文本:从字面上看,我想删除的是"\\n" ,(包括逗号和引号),那么什么才能作为第二个参数传递才能使其正常工作?

Thanks in advance. 提前致谢。

You need to escape the quotes, if you use double quotes for the first argument to replace 如果将第一个参数replace为双引号,则需要转引号

'some text "\\n", more text'.replace("\\"\\n\\",", 'new content');

or you can do 或者你可以做

'some text "\\n", more text'.replace('"\\n",', 'new content');

Note in the second example, the first argument to replace uses single quotes to denote the string, so you don't need to escape the double quotes. 请注意,在第二个示例中,replace的第一个参数使用单引号表示字符串,因此您无需转义双引号。

Finally, one more option is to use a regex in the replace invocation 最后,另一个选择是在replace调用中使用正则表达式

'some text "\\n", more text "\\n",'.replace(/"\\n",/g, 'new content');

the "g" on the end makes the replace a replace-all (global). 末尾的“ g”表示全部替换(全局)。

To remove "\\n" , simply use String.replace : 要删除"\\n" ,只需使用String.replace

srcString.replace(/"\n"[,]/g, "")

You can replace using the Regular Expression /"\\n"[,]/g 您可以使用正则表达式/"\\n"[,]/g替换

There is no need for such a function. 不需要这种功能。 The replace function has an extra parameter g , which replaces ALL occurrences instead of the first one: replace函数有一个额外的参数g ,它将替换所有出现的内容,而不是第一个出现的内容:

'sometext\nanothertext'.replace(/\n/g,'');

Regardless of whether the quotes within the string are escaped or not: 不管字符串中的引号是否被转义:

 var str = 'This string has a "\n", quoted newline.';

or 要么

var str = "This string has a \"\n\", escaped quoted newline.";

The solution is the same (change '!!!' to what you want to replace "\\n", with: 解决方法是相同的(将“ !!!”更改为要替换为"\\n",用:

 str.replace(/"\n",/g,'!!!');

jsFiddle Demo jsFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM