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

regex - Writing double quotes in javascript string - Stack Overflow

programmeradmin0浏览0评论

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 ma and the quotes), so what to pass as second param in order to make it work properly?

Thanks in advance.

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 ma and the quotes), so what to pass as second param in order to make it work properly?

Thanks in advance.

Share Improve this question edited Aug 7, 2012 at 13:59 Code Jockey 6,7216 gold badges36 silver badges45 bronze badges asked Aug 7, 2012 at 13:04 Jorge Antonio Diaz-BenitoJorge Antonio Diaz-Benito 1,06613 silver badges33 bronze badges 1
  • 2 This is horribly inefficient and not necessary because you can use a regex with the global flag. – Esailija Commented Aug 7, 2012 at 13:12
Add a ment  | 

4 Answers 4

Reset to default 7

You need to escape the quotes, if you use double quotes for the first argument to 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.

Finally, one more option is to use a regex in the replaceinvocation

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

the "g" on the end makes the replace a replace-all (global).

To remove "\n", simply use String.replace:

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

You can replace using the Regular Expression /"\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:

'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:

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

jsFiddle Demo

发布评论

评论列表(0)

  1. 暂无评论