admin管理员组文章数量:1321070
Why do they use
/
instead of
'
in JavaScript string replace()? E.g.:
document.write(str.replace(/hi/, "hey"));
Why do they use
/
instead of
'
in JavaScript string replace()? E.g.:
document.write(str.replace(/hi/, "hey"));
Share
Improve this question
asked Apr 25, 2009 at 11:01
AlexAlex
44.7k48 gold badges100 silver badges127 bronze badges
2 Answers
Reset to default 10because // denotes a Regex, which is a much more powerful version of string searching/replacing than a simple Replace("x","y")
But also supports simple patterns.
var a = "xxx";
var b = a.replace(/x/,'y');
alert( b ); //alerts "yxx"
adding the g modifier to replace globaly would be:
b = a.replace(/x/g,'y');
alert(b); //alerts "yyy"
You can also add the i modifier to make it case-insensitive.
var a = "XXX";
b = a.replace(/x/gi,'y');
alert(b); // alerts "yyy";
https://developer.mozilla/En/Core_JavaScript_1.5_Guide/Regular_Expressions
The JavaScript method replace()
allows both a plain string and a RegExp object as the search part.
And in your example a regular expression is used (RegExp literal syntax) although a plain string would suffice.
本文标签: Slashes instead of quotes in JavaScript string replace methodStack Overflow
版权声明:本文标题:Slashes instead of quotes in JavaScript string replace method - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742092264a2420337.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论