replace()方法使用函数做替代字符串的说明

来源:互联网 发布:linux安全策略与实例 编辑:程序博客网 时间:2024/05/17 20:28
    在 JavaScript 脚本中,如果 replace() 方法中使用了函数,其参数说明如下:
    
    形式: string.replace(RegExp, function(a, [b1, b2, b3, ...] c, d) {} );
    说明: 
                    string 是要搜索的字符串;
                    RegExp 是要对字符串进行匹配的正则表达式;
                    a 是匹配的子字符串;
                    [b1, b2, b3, ...] 是指RegExp中从左向右每个小括号中匹配的值;
                    c 是匹配的子字符串相对字符串开始位置的偏移量;
                    d 是要搜索的字符串本身。
 
    MSDN 上的解释:

If replaceText is a function, for each matched substring the function is called with the following m + 3 arguments where m is the number of left capturing parentheses in the rgExp. The first argument is the substring that matched. The next m arguments are all of the captures that resulted from the search. Argument m + 2 is the offset within stringObj where the match occurred, and argument m + 3 is stringObj. The result is the string value that results from replacing each matched substring with the corresponding return value of the function call.
                 
    请看下面的代码:
 
 
    运行的结果如下:
 
 
    b2 变量这时是没有值的,如果把第15行的“212F”改为“21.2F”,代码如下:
 
 
    注意第15行代码,这时的运行结果如下:
 
 
    这时的变量 b2 的值变成了“.2”(在第二次匹配中),而这正是正则表达式“(/./d*)”的匹配字符串。
    所以,如果正则表达式的括号有第三对、第四对...,那么变量组将会有b3, b4...等等。
    这就是 replace() 方法函数的返回参数列表情况。


又找到了一段中文的说明:

如果 replaceText 是一个函数,对于每个匹配的子字符串,调用该函数时带有下面的 m + 3 个参数,这里 m 是在 rgExp 中用于捕获的左括弧的个数。第一个参数是匹配的子字符串。接下来的 m 个参数是搜索中捕获到的全部结果。参数 m + 2 是当前字符串对象中发生匹配位置的偏移量,而参数 m + 3 是当前字符串对象。结果为将每一匹配的子字符串替换为函数调用的相应返回值后的字符串值。
 
原创粉丝点击