JavaScript function replace

Source: Internet
Author: User

The replace function accepts two parameters. The first parameter is a string or regular expression. The first parameter can also accept a string or a function.

First, if the first parameter is a string, we no longer need to say "I am a boy". replace ("boy", "girl"), and output: "I am a girl ". The first parameter is the regular expression. For a regular expression, the replacement behavior is first determined based on whether or not the global (Global // g) is used. If it is all, It is replaced with all. If it is not global, only the first matched string is replaced. For example:

Copy codeThe Code is as follows:
"Ha". replace (/\ B \ w + \ B/g, "He") // He

"Ha". replace (/\ B \ w + \ B/, "He") // He Ha

1: The second parameter is a string:

A special identifier for the regular expression replace $:

1. $ I (I: 1-99): indicates the text matched by the regular expression from left to right.
2. $ &: indicates the full text that matches the regular expression.
3. $ '(': Switch skill key): indicates the left text that matches the string.
4. $ '(': single quotes): indicates the right text matching the string.
5. $: Indicates $ transfer.
Below are several demos:
Copy codeThe Code is as follows:
"Boy & girl ". replace (/(\ w +) \ s * & \ s * (\ w +)/g, "$2 & $1") // girl & boy

"Boy". replace (/\ w +/g, "$ &-$ &") // boy-boy

"Javascript". replace (/script/, "$ &! = $ '") // Javascript! = Java

"Javascript". replace (/java/, "$ & $ 'is") // javascript is script

2: The second parameter is the function:

We recommend that you use the Function Method in ECMAScript3. This function is implemented in JavaScript1.2. this function is called every time the replace method is executed. The returned value is the new value to be replaced.

Function parameters:

1. The first parameter is the full text ($ &) of each match &).
2. The intermediate parameter is a sub-expression that matches a string, and the number is not limited. ($ I (I: 1-99 ))
3. The second to last parameter is the position of the matched subscript matching the text string.
4. The last parameter indicates the string itself.
This is what we want to talk about in this article where replace is powerful. The theoretical things are all dry, and we need examples to solve all the holes:

1: uppercase letters of the string:

Copy codeThe Code is as follows:
String. prototype. capitalize = function (){

Return this. replace (/(^ | \ s) ([a-z])/g, function (m, p1, p2) {return p1 + p2.toUpperCase ();

});

};
Console. log ("I am a boy! ". Capitalize ())

Output: I Am A Boy!

2: extract and summarize the scores of the string "Zhang San 56 points, Li Si 74 points, Wang wu92 points, and Zhao liu84 points", calculate the average score, and output the average score gap of each person.

Copy codeThe Code is as follows:
Var s = "Zhang San 56 points, Li Si 74 points, Wang wu92 points, Zhao liu84 points ";

Var a = s. match (/\ d +/g );

Var sum = 0;

For (var I = 0; I <a. length; I ++ ){

Sum + = parseFloat (a [I]);

}



Var avg = sum/a. length;



Function f (){

Var n = parseFloat (arguments [1]);

Return n + "points" + "(" + (n> avg )? ("Average score exceeded" + (n-avg )):

("Lower than average score" + (avg-n) + "points )";

}



Var result = s. replace (/(\ d +)/g, f );

Console. log (result );

Output:

John scored 56 points (less than the average score of 20.5 points), Li scored 74 points (less than the average score of 2.5 points), Wang wu92 points (more than the average score of 15.5 points), and Zhao liu84 points (more than the average score of 7.5 points)

In addition to regular expressions, the replace function of JavaScript will send back more powerful applications. Here, we will not go into regular expressions such as advanced application assertions.

Source: http://www.cnblogs.com/whitewolf/

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.