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

Slashes instead of quotes in JavaScript string replace method - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 10

because // 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.

发布评论

评论列表(0)

  1. 暂无评论