gpt4 book ai didi

javascript - 有没有字符串的拼接方法?

转载 作者:IT王子 更新时间:2023-10-29 02:50:34 26 4
gpt4 key购买 nike

Javascript splice 只适用于数组。字符串有类似的方法吗?还是我应该创建自己的自定义函数?

substr()substring() 方法只会返回提取的字符串,不会修改原始字符串。我想要做的是从我的字符串中删除一些部分并将更改应用于原始字符串。此外,方法 replace() 在我的情况下不起作用,因为我想删除从索引开始到其他索引结束的部分,就像我可以用 splice( ) 方法。我尝试将我的字符串转换为数组,但这不是一个巧妙的方法。

最佳答案

将字符串切片两次会更快,如下所示:

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一般功能的功能,但针对提问者提出的情况优化了代码(即,不向修改后的内容添加任何内容) string) 不会改变各种方法的相对性能。

关于javascript - 有没有字符串的拼接方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20817618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com