JavaScript String Object Method replace

Source: Internet
Author: User

    • The simplest use of replace is:
var str = ' aaaaa9876b0000 '; str.replace (/a/g, ' a ');
    • Sometimes we want to just add a specific character in a matching location:
var str = ' aaaaa9876b0000 '; Str.replace (/([0-9])/g, ' [$] ');

These results are:

AAAAA[9][8][7][6]B[0][0][0][0]
    • If we want to make a mathematical calculation of the matching position, then we can change the second parameter to a function whose return value is the character to be changed in the corresponding position:
' abc123ba0c '. Replace (/([0-9])/g,function(m) {return 2*parseint (m)})

These results are:

abc246ba0c

So, what are the parameters of this function?

The first parameter represents a matching complete string, equivalent to/([0-9]) after the global execution of the Exec method of/g, as follows:

>var reg =/([0-9])/g
>reg.exec (' abc123ba0c ') ["1", "1"]>reg.exec (' abc123ba0c ') ["2", "2"]> Reg.exec (' abc123ba0c ') ["3", "3"]>reg.exec (' abc123ba0c ') ["0", "0"]

How many () regular expressions There are, and how many arguments can be followed by M, which represent the contents of the corresponding position in the above matching results.

After the parameters in these (), there is also a parameter that represents the starting point of all globally matched string m in the original string:

> ' abc123ba0c '. Replace (/([a-z]+) ([0-9]+)/g,function(M,P1,P2,P3,P4) {Console.log (m+ ' + p1 + ' +p2+ ' +  123 00 6

JavaScript String Object Method replace

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.