1

Why do they use

/

instead of

'

in JavaScript string replace()? E.g.:

document.write(str.replace(/hi/, "hey"));

2 Answers 2

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.org/En/Core_JavaScript_1.5_Guide/Regular_Expressions

Sign up to request clarification or add additional context in comments.

1 Comment

Good, comprehensive answer! +1
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.