所以,我有一个函数有两个参数:字符串和匹配索引要替换,我需要替换只匹配该索引.我怎样才能做到这一点?
例:
replace('a_a_a_a_a', 1)
Run Code Online (Sandbox Code Playgroud)
结果:
a__a_a_a
Run Code Online (Sandbox Code Playgroud)
jAn*_*ndy 12
看起来像:
var mystr = 'a_a_a_a_a';
function replaceIndex(string, at, repl) {
return string.replace(/\S/g, function(match, i) {
if( i === at ) return repl;
return match;
});
}
replaceIndex(mystr, 2, '_');
Run Code Online (Sandbox Code Playgroud)
上面的代码使用了事实,.replace()可以将funarg(函数参数)作为第二个参数.该回调在匹配的正则表达式模式的当前匹配和该匹配的索引(以及我们在此不感兴趣的其他一些)中传递.现在,这是我们完成所需结果所需的所有信息.我们写一个小功能愿望需要三个参数:
对于像我这样认为正则表达式是神秘的人来说,这里也是"纯JavaScript"方式:
function CustomReplace(strData, strTextToReplace, strReplaceWith, replaceAt) {
var index = strData.indexOf(strTextToReplace);
for (var i = 1; i < replaceAt; i++)
index = strData.indexOf(strTextToReplace, index + 1);
if (index >= 0)
return strData.substr(0, index) + strReplaceWith + strData.substr(index + strTextToReplace.length, strData.length);
return strData;
}
Run Code Online (Sandbox Code Playgroud)
用法:
var mystr = 'a_a_a_a_a';
var newstr = CustomReplace(mystr, "_", "__", 2); //replace the second appearance
Run Code Online (Sandbox Code Playgroud)
现场测试案例:http://jsfiddle.net/tXx5n/2/
| 归档时间: |
|
| 查看次数: |
10917 次 |
| 最近记录: |