将字符串切片两次会更快,如下所示:
function spliceSlice(str, index, count, add) {
// We cannot pass negative indexes directly to the 2nd slicing operation.
if (index < 0) {
index = str.length + index;
if (index < 0) {
index = 0;
}
}
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
而不是使用拆分后跟连接(Kumar Harsh的方法),如下所示:
function spliceSplit(str, index, count, add) {
var ar = str.split('');
ar.splice(index, count, add);
return ar.join('');
}
这是一个jsperf,比较了这两个和其他几个方法。(jsperf已经关闭了几个月了。请在评论中提出替代方案。
尽管上面的代码实现了重现 的一般功能的函数,但针对提问者呈现的情况优化代码(即,不对修改后的字符串添加任何内容)不会改变各种方法的相对性能。splice