Home > Web Front-end > JS Tutorial > body text

JavaScript implements replaceall global matching and replacement examples

黄舟
Release: 2017-12-05 09:47:12
Original
2001 people have browsed it

In the previous article, we introduced to you an example of the replaceall method in jQuery. I believe that my friends have a better understanding of the use of replaceall, so today we will continue to introduce to you about JavaScriptAn example of implementing replaceall global matching and replacement!

ReplaceStringin javascript uses the replacefunction, but during actual use, it is found that this function will only replace the first matched character. This makes people very unhappy. In the PHP language, replace can achieve global matching and replacement. No way, after careful study, I 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.php.cn');
Copy after login

or:

str.replace(new RegExp('www.baidu.com','gm'),'www.php.cn');
Copy after login

Replace all www.baidu.com in str characters with php.cn

(2) Expand the js function library yourself and create your own function replaceall method to achieve global matching and replace the function. As follows:

String.prototype.replaceall=function(s1,s2){ 
    return this.replace(new RegExp(s1,"gm"),s2);  
}
Copy after login


This actually uses the idea of ​​method one. An example is as follows (the same function as above is also implemented here, but it is more intuitive than method one):

str.replace('www.baidu.com','www.php.cn');
Copy after login

Summary:

This article introduces to you through examples the JavaScript implementation of replaceall global matching and replacement. I believe that my friends also have a certain understanding of this. I hope it will be helpful to your work!

Related recommendations:

Example analysis of the replaceAll() method in jQuery


js uses regular expressions to implement ReplaceAll replacement method


jQuery.replaceAll() function example detailed explanation


##js replace and replaceall instance usage detailed explanation

The above is the detailed content of JavaScript implements replaceall global matching and replacement examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!