Preface: Do you have such trouble: If you want to replace all the parts of the String that meet the criteria with a specified String, for example, replace all the character ‘A’ in “aabbccda” with an ‘*’, and then search all the methods of String, only replace can be found, but replace can only replace the first matching character, a. There’s only some other way to do it all. How come there is no substitution method in JS? Well, here it is today –replaceAll.

  • Limitations of String.prototype.replace

As mentioned in the introduction, when we want to replace the “A” in the string “aabbccda” with an “*”, the method that comes to mind is replace, but look at the definition of the replace method:

The replace() method returns a new string that replaces some or all of the pattern matches with the replacement value. The pattern can be a string or a regular expression, and the replacement value can be a string or a callback function that is called on every match. If pattern is a string, only the first match is replaced.

So, if you replace directly with the replace method, only the first value that satisfies the condition is replaced:

'aabbccda'.replace('a'.The '*'); // "*abbccda"
Copy the code

So how do you replace all the “A” s? The following two methods are commonly used: (1) Regular expressions

'aabbccda'.replace(/a/g.The '*'); // "**bbccd*"
Copy the code

(2) String split method

'aabbccda'.split('a').join(The '*'); // "**bbccd*"
Copy the code

Although the above two methods can achieve the goal of complete replacement, is there a more direct method?

  • String.prototype.replaceAll

The replaceAll approach is currently in stage4 and is expected to be released in ES2021. It’s as simple to use as Replace:

The replaceAll() method returns a new string, all parts of which meet pattern are replaced by replacement. Pattern can be a string or a RegExp, replacement can be a string or a function that is called each time a match is made. The original string remains the same.

Grammar:

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

Then, the aforementioned problem can be solved with the replaceAll method:

'aabbccda'.replaceAll('a'.The '*'); // "**bbccd*"
Copy the code

Isn’t that simple, but there are a few things to note when using the replaceAll method:

Pay special attention to 📢 : if the regexp | substr for a non-global regular expressions, the replaceAll throw an error.

'aabbccda'.replaceAll(/a/.The '*'); // Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument
Copy the code

Why do I get an error?

The replaceAll method replaces all, but the regular expression is non-global, so the compiler doesn’t know what to do with it, so it will report an error.

  • That’s how replaceAll works. Have you learned how to use it?