First look at the introduction in MSDN
Replace method
Returns the copy of a string that is replaced with text based on a regular expression.
Stringobj.replace (Rgexp, ReplaceText)
Parameters
Stringobj
Required option. The string object or string literal to perform the substitution. The string is not modified by the Replace method.
Rgexp
Required option. Is the regular expression object that contains the regular expression pattern or the available flags. It can also be a String object or text. If Rgexp is not a regular expression object, it is converted
As a string, and make an exact lookup; Do not attempt to convert a string to a regular expression.
ReplaceText
Required option. is a string object or string literal, and the position in each matching rgexp in Stringobj is replaced with the text contained in that object. In Jscript 5.5
or later, the ReplaceText parameter can also be a function that returns the replacement text. If ReplaceText is a function, for each matched substring, the function is called with the
There are the following M + 3 parameters, where m is the number of left parentheses to capture in the rgexp. The first argument is a matching substring. The next m parameter is captured in the search
To the full results. The parameter M + 2 is the offset of the matching position in the current string object, and the parameter M + 3 is the current string object. The result is that each matched substring is replaced
The string value that is replaced by the corresponding return value of the function call.
In fact, the light so to see, must be confused, let us give a few examples, unlock the mystery of replace
EXP1:
This is the most common, and also the simplest. I'm going to steal the MSDN example directly.
function ReplaceDemo()...{
var r, re; //Declare variables.
var ss = "The man hit the ball with the bat.";
re = /The/g; //Create regular expression pattern.
r = ss.replace(re, "A"); //Replace "The" with "A".
return(r); //Return string with replacement made.
}
This function returns the "A man hit the ball with the bat." This string. In fact, here is a little bit of money for small use, we can directly
re =/the/g; Create Regular expression pattern.
r = Ss.replace (Re, "A"); Replace "The" with "A".
Change to R = Ss.replace ("The", "a"); The end result is the same, this is simpler, there is nothing to say, to note that the SS is unchanged after the Ss.replace ("The", "a")
, or "The man hit the ball with the bat.", except that this method returns a new string.
EXP2:
function ReplaceDemo()...{
var r, re; //Declare variables.
var ss = "The rain in Spain falls mainly in the plain.";
re = /(S+)(s+)(S+)/g; //Create regular expression pattern.
r = ss.replace(re, "$3$2$1"); //Swap each pair of words.
return(r); //Return resulting string.
}