Home  >  Article  >  Web Front-end  >  javascript regular replacement replace(regExp, function) usage_javascript skills

javascript regular replacement replace(regExp, function) usage_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:26:321357browse
Copy code The code is as follows:

function fn()
{
for(var i = 0;i < arguments.length;i ){
 alert("The value of the" (i 1) "th parameter: " arguments[i]);
 }
}
var str = '
{ni}
';
str.replace(/{([a-z] )}/ig, fn);


According to the output results of multiple tests, it can be concluded that in fn:

The first parameter is the matched string, such as {wo} and {ni};

The second parameter can have 0-N, which matches a bracketed regular string in the first parameter. For example, wo and ni in the first parameter can match ([a-z] ),

There are several groups of brackets, and there are several parameters;

The third parameter is the position of the string matched in the first parameter, such as {wo} returns 9, {no} returns 16;

The fourth parameter is the string used to match, in this example it is
{ni}
.

In this example, for a json object containing wo and ni, you can simply use:

Copy code The code is as follows :

str.replace(/{([a-z] )}/ig, function(s, t){
return json[t];
});

to replace.
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