edotassi
edotassi

Reputation: 476

String replace with regex, ie strange results

Why i have this results?

"hello world".replace(/[']/gi, "\\'"); // on chrome => "hello world"
"hello world".replace(/[']/gi, "\\'"); // on ie => "hello world"

"hello world".replace((/[']/gi).compile(), "\\'"); // on chrome => "hello world"
"hello world".replace((/[']/gi).compile(), "\\'"); // on ie => "\'hello world"

Chrome: 43.0.2357.124 m

IE: 11.0.10011.0

Upvotes: 0

Views: 54

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

You're misusing the compile method.

Warning: The compile method is deprecated, you shouldn't use it. Create a new RegExp object instead.

It's prototype reads:

regexObj.compile(pattern, flags)

So you have to pass it a new pattern that will replace the instance's pattern.

  • Under IE, calling compile() yields the regex /(?:)/ which is an empty regex that matches the empty string at the start of "hello world". There's no g flag either, so you end up with \' prepended to the string.

  • Under Chrome, compile() returns undefined, so no replacement is made.

Upvotes: 3

Related Questions