Home >Web Front-end >JS Tutorial >Detailed explanation on the use of replace of String object in js_javascript skills

Detailed explanation on the use of replace of String object in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:06:281174browse

Today when I was reading the source code stringH of Qwrap, there was a

copy code 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] || '';
});
}

The way to use it is:
alert(format("{0} love {1}.", 'I','You'))//I love you The implementation of
format mainly uses the replace method of the String object:

replace: Returns the characters after text replacement according to the regular expression Copy of string.

1. Commonly used replacement
Copy code The code is as follows:

function ReplaceDemo(){
var r, re; // Declare variables.
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 Regular expression pattern.
r = ss.replace(re, "A"); // Replace "The" with "A".
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. Subexpression in replacement pattern
Copy code The code is as follows:

function ReplaceDemo(){
var r, re ; // Declare variables.
var ss = "The rain in Spain falls mainly in the plain.";
re = /(S )(s )(S )/g; // Create a regular expression pattern.
r = ss.replace(re, "$3$2$1"); // Swap each pair of words.
return(r); // Return the result string.
}
document.write(ReplaceDemo()); //rain The Spain in mainly falls the in plain.

Matching regular items: The rain, in Spain, falls mainly ,in the;Execute ss.replace(re, "$3$2$1") operation to complete the exchange of word positions

$1 matches the first (S)

$2 matches (s )

$3 matches the second (S )

3.replace when the second parameter is function

Copy code The code is as follows:

function f2c(s){
var test = /(d (.d*)?)Fb/ 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 212,3,.2,2.2
$2 matches the last .2
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn