Javascript uses regular expressions to ReplaceAll _ javascript skills

Source: Internet
Author: User
JS does not provide methods such as replaceAll. Using a regular table can achieve the Replace effect. If you are interested, check that the following sample JS string contains the replace () method. However, this method only replaces the first matched string. For example:

 New Document 《script》var str = "wordwordwordword";var strNew = str.replace("word","Excel");alert(strNew);《script》

If you want to replace all of them, JS does not provide the replaceAll method. You can use a regular table to achieve the effect of Replace:

str.replace(/word/g,"Excel")

G indicates that the global match is executed (search for all matches instead of stopping the first match ).

 New Document 《script》function replaceAll(str){if(str!=null)str = str.replace(/word/g,"Excel")return str;}《script》《script》var str = "wordwordwordword";var strNew = str.replace("word","Excel");strNew = replaceAll(str);alert(strNew);《script》

The preceding method is similar to the following:

str.replace(new RegExp("word","gm"),"Excel")

G ).

M.

In addition, you can also add the Stirng object prototype method:

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


In this way, you can use replaceAll just like using the replace method.

str.replaceAll("word","Excel");

To sum up, there are three methods:

1. str. replace (/oldString/g, newString)

2. str. replace (new RegExp (oldString, "gm"), newString)

3. added the String object Prototype Method replaceAll.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.