1

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?

2
  • Check the compatibility table on MDN. Commented 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. Commented Jul 5, 2020 at 12:47

1 Answer 1

3

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

enter image description here

Something like:

if (!String.prototype.replaceAll)
{
    String.prototype.replaceAll = function(search, replace){
      return this.split(search).join(replace);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Not supported in the latest version of Chrome.😥😥😥😥
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.
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.

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.