JS implementation of ReplaceAll method

Source: Internet
Author: User

The JS string has the Replace () method. However, this method replaces only the first string that is matched to. The following example:

<HTML><HEAD><TITLE> New Document </TITLE></HEAD><BODY><script>    var"wordwordwordword";    var strnew = str.replace ("word","Excel" );   alert (strnew); </script></BODY></HTML>

If you want to replace all, JS does not provide replaceall such a method. Use regular tables to achieve the effect of replace:

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

the meaning of G is to perform a global match (find all matches rather than stop after the first match is found).

<HEAD><TITLE> New Document </TITLE><script>function ReplaceAll (str) {if(str!=NULL) Str= Str.replace (/word/g,"Excel")    returnstr;}</script></HEAD><BODY><script>varstr ="Wordwordwordword"; varStrnew = Str.replace ("Word","Excel"); Strnew=ReplaceAll (str); alert (strnew);</script></BODY></HTML>

There is a similar wording in the above:

Str.replace (new RegExp ("word","GM")," Excel ")

G performs a global match (finds all matches rather than stops after the first match is found).

M performs multi-line matching.

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

String.prototype.replaceAll  = function (s1,s2) {       returnthis. replace (new RegExp (S1,"GM"), S2);   

This allows you to use ReplaceAll as you would with the Replace method.

Str.replaceall ("word","Excel");

Sum up, three ways

1. Str.replace (/oldstring/g,newstring)

2. Str.replace (New RegExp (oldstring, "GM"), newstring)

3. Adding a 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.