For details about how to use the String object replace, refer. Today, when I was reading the source code stringH of Qwrap, there was
The Code is as follows:
Format: function (s, arg0 ){
Var args = arguments;
Return s. replace (/\ {(\ d +) \}/ig, function (a, B ){
Return args [(B | 0) + 1] | '';
});
}
It is used in the following ways:
Alert (format ("{0} love {1}.", 'I', 'you') // I love You
The format implementation method mainly uses the String object's replace method:
Replace: returns the string copy after text replacement based on the regular expression.
1. Commonly Used replace
The Code is as follows:
Function ReplaceDemo (){
Var r, re; // declare the variable.
Var ss = "The man hit the ball with the bat. \ n ";
Ss + = "while the fielder caught the ball with the glove .";
Re =/The/g; // create The regular expression mode.
R = ss. replace (re, "A"); // replace "The" with "".
Return (r); // return the replaced string.
}
ReplaceDemo (); // A man hit the ball with the bat. while the fielder caught the ball with the glove.
2. Replace the subexpression in the Mode
The Code is as follows:
Function ReplaceDemo (){
Var r, re; // declare the variable.
Var ss = "The rain in Spain falls mainly in the plain .";
Re =/(\ S +) (\ s +) (\ S +)/g; // create the regular expression mode.
R = ss. replace (re, "$3 $2 $1"); // exchange each pair of words.
Return (r); // return the result string.
}
Document. write (ReplaceDemo (); // rain The Spain in mainly falls the in plain.
Match The regular expression items: the rain, in Spain, falls mainly, in The; executes the ss. replace (re, "$3 $2 $1") operation to complete The word position exchange.
$1 matches the first (\ S +)
$2 matches (\ s +)
$3 matches the second (\ S +)
3. When the second parameter of replace is function
The Code is as follows:
Function f2c (s ){
Var test =/(\ d + (\. \ d *)?) F \ B/g; // initialization mode.
Return (s. replace (test, function ($0, $1, $2) {return ($1-32) + "C ");}));
}
F2c ("Water boils at 212F 3F. 2F 2.2F. 2"); // Water boils at 180C-29C.-30C-29.8C. 2
$0 matches 212F, 3F,. 2F, 2.2F
$1 matches 2.2
$2 match the last. 2