javascript implements a global match and replace method

  • 2020-06-01 08:18:02
  • OfStack

The replace function is used to replace the javascript string, but in practice it only replaces the first character that is matched, which is annoying. In the php language, replace implements global matching and substitution. No way, a careful study, found that there are other ways to achieve global matching and replacement.

(1) in fact, replace itself can also achieve this function, but it needs to add a parameter g in a regular form, for example:



str.replace(new RegExp('','gm'),'');

Replace all in str with

(2) expand the js function library, and create the replaceall method to achieve global matching and replacement. As follows:

    return this.replace(new RegExp(s1,"gm"),s2); 

This is actually using the idea of method 1. Here's an example (it does the same thing here, but it's more intuitive than method 1) :


That's all for this article, I hope you enjoy it.

Related articles: