问题描述
Javascript splice
仅适用于数组。字符串有类似的方法吗?或者我应该创建自己的自定义函数吗?
substr()
和 substring ()
方法只返回提取的字符串而不修改原始字符串。我想要做的是从我的字符串中删除一些部分并将更改应用于原始字符串。此外,方法 replace()
在我的情况下不起作用,因为我想删除从索引开始并以某个其他索引结束的部分,就像我可以用 splice()
方法。我尝试将我的字符串转换为数组,但这不是一个简洁的方法。
将字符串切片两次更快,像这样:
function spliceSlice(str,index,count,add){
//我们不能传递负数直接索引到第二个切片操作。
if(index< 0){
index = str.length + index;
if(index< 0){
index = 0;
}
}
返回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现在已经停止了几个月。请在评论中提出备选方案。)
虽然上面的代码实现了重现 general 的函数 splice
的功能,优化提问者提供的案例代码(即,不对修改后的字符串添加任何内容)不会改变各种方法的相对性能。 / p>
The Javascript splice
only works with arrays. Is there similar method for strings? Or should I create my own custom function?
The substr()
, and substring()
methods will only return the extracted string and not modify the original string. What I want to do is remove some part from my string and apply the change to the original string. Moreover, the method replace()
will not work in my case because I want to remove parts starting from an index and ending at some other index, exactly like what I can do with the splice()
method. I tried converting my string to an array, but this is not a neat method.
It is faster to slice the string twice, like this:
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);
}
than using a split followed by a join (Kumar Harsh's method), like this:
function spliceSplit(str, index, count, add) {
var ar = str.split('');
ar.splice(index, count, add);
return ar.join('');
}
Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)
Although the code above implements functions that reproduce the general functionality of splice
, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.
这篇关于字符串是否有拼接方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!