Third parameter for String.replace

# Biju (13 years ago)

Right now

var haystack = "Foo Bar foo bar foo bar"; var needle = "bar"; var result = haystack.replace(needle, "---");

gives ==> "Foo Bar foo --- foo bar"

ie, it will only replace first occurrence "bar"

and to get all occurrence "bar" replaced and that too with no case sensitivity we need to pass a RegExp to the "needle" like

"Foo Bar foo bar foo bar".replace(/bar/ig, "---");

But many times the "needle" may a variable populated from user input. Hence the ordinary web developer will have burden of converting input text to RegExp. Most of the webdev are not so comfortable with RegExp, and they will start writing complex logic. Which many times will have some bug on certain value of content text. (that what I see, at work I support/maintain many intranet apps )

So I have proposal, can we have 3rd parameter for replace() function? like

haystack.replace(needle, newText, regexpFlag);

where regexpFlag is the flag part of the RegExp. And if "needle" is a string will be used to make the match characters after "escaping" special characters like *?.()[]{}^$|/

# gaz Heyes (13 years ago)

On 6 March 2012 05:35, Biju <bijumaillist at gmail.com> wrote:

So I have proposal, can we have 3rd parameter for replace() function? like

haystack.replace(needle, newText, regexpFlag);

where regexpFlag is the flag part of the RegExp. And if "needle" is a string will be used to make the match characters after "escaping" special characters like *?.()[]{}^$|/

No no no no nooooooooooooooooo. This is already one of the best functions in JavaScript but has been really badly designed. This suggestion makes it worse.

< www.thespanner.co.uk/2010/09/27/string-replace-javascript-bad-design>

Even Twitter devs seemed to struggle with using it correctly to fix a DOM xss issue.

# Biju (13 years ago)

I am happy with Mozilla do if all browsers do that way..

Alternately, I will be also happy to take, if

"Foo Bar foo bar foo bar".replace("bar", "---");

gives ==> "Foo --- foo --- foo ---"

ie, the replace is global and case insensitive. practically most time that is what web developer want. and many old languages use to do that way.