admin管理员组文章数量:1414894
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
4 Answers
Reset to default 7You 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 replace
invocation
'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
本文标签: regexWriting double quotes in javascript stringStack Overflow
版权声明:本文标题:regex - Writing double quotes in javascript string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745188047a2646776.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论