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(/www.baidu.com/g,'www.ofstack.com');

Or:


str.replace(new RegExp('www.baidu.com','gm'),'www.ofstack.com');

Replace all www.baidu.com in str with www.ofstack.com

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


String.prototype.replaceall=function(s1,s2){
    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) :


str.replace('www.baidu.com','www.ofstack.com');

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


Related articles: