I didn't see replaceAll in String.prototype,but MDN has mentioned this function.When i use it,it will throw a TypeError:xxx.replaceAll is not a function?Is replaceAll the future ECMA standard?
-
Check the compatibility table on MDN.trincot– trincot2020-07-05 12:34:07 +00:00Commented Jul 5, 2020 at 12:34
-
See the TC39 proposals list. It’ll be part of the ECMAScript 2021 standard which will be officially released in a year.Sebastian Simon– Sebastian Simon2020-07-05 12:47:27 +00:00Commented Jul 5, 2020 at 12:47
Add a comment
|
1 Answer
Check your browser. This method is pretty new, so it's not advisable to use it yet (or implement substitute if it's not supported by current browser)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Something like:
if (!String.prototype.replaceAll)
{
String.prototype.replaceAll = function(search, replace){
return this.split(search).join(replace);
}
}
3 Comments
oxygen
Not supported in the latest version of Chrome.😥😥😥😥
Sebastian Simon
Oh, that polyfill (well, it isn’t really one) isn’t correct for most regular expressions. Anything with capture groups is likely going to produce different results and any non-global regex won’t fail, as it should, according to spec. Using the empty string will also produce different results.
stwr667
This is a simpler alternative:
"Substitute X".replace(/X/g, "me"). Also more performant than split and join. See caniuse.com/mdn-javascript_grammar_regular_expression_literals.