有string的拼接方法吗?

JavaScript splice仅适用于数组。 有没有类似的方法为string? 还是应该创build我自己的自定义函数?

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

将string分割两次会更快,如下所示:

 function spliceSlice(str, index, count, add) { // We cannot pass negative indexes dirrectly 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); } 

比使用分裂,然后join(Kumar Harsh的方法),如下所示:

 function spliceSplit(str, index, count, add) { var ar = str.split(''); ar.splice(index, count, add); return ar.join(''); } 

这里是一个jsperf比较两个和其他一些方法。 (jsperf现在已经停了几个月了,请在评论中提出替代scheme。)

尽pipe上面的代码实现了重现splice一般function的函数,但优化了提问者呈现的情况下的代码(即,不向修改后的string添加任何内容)并不会改变各种方法的相对性能。

编辑

这当然不是“拼接”一个string的最好方法,我已经把它作为实现的一个例子,这是split(),splice()和join()中的缺陷和非常明显的例子。 为了更好地实现,请参阅路易斯的方法。


不,没有String.splice这样的东西,但你可以试试这个:

 newStr = str.split(''); // or newStr = [...str]; newStr.splice(2,5); newStr = newStr.join(''); 

我意识到在数组中没有splicefunction,所以你必须把string转换成数组。 运气不好

这里有一个可爱的小咖喱,可以提高可读性(恕我直言):

第二个函数的签名与Array.prototype.splice方法相同。

 function mutate(s) { return function splice() { var a = s.split(''); Array.prototype.splice.apply(a, arguments); return a.join(''); }; } mutate('101')(1, 1, '1'); 

我知道已经有一个可以接受的答案,但是希望这是有用的。

方法路易斯的答案,作为一个String原型函数:

 String.prototype.splice = function(index, count, add) { if (index < 0) { index = this.length + index; if (index < 0) { index = 0; } } return this.slice(0, index) + (add || "") + this.slice(index + count); } 

例:

  > "Held!".splice(3,0,"lo Worl") < "Hello World!" 

我想提供一个简单的替代库马/科迪和路易斯的方法。 在我运行的所有testing中,它的执行速度与Louis方法一样快(请参阅基准testing的小提琴testing)。

 String.prototype.splice = function(startIndex,length,insertString){ return this.substring(0,startIndex) + insertString + this.substring(startIndex + length); }; 

你可以像这样使用它:

 var creditCardNumber = "5500000000000004"; var cardSuffix = creditCardNumber.splice(0,12,'****'); console.log(cardSuffix); // output: ****0004 

查看testing结果: https : //jsfiddle.net/0quz9q9m/5/

只需使用substr为string

恩。

 var str = "Hello world!"; var res = str.substr(1, str.length); 

结果= ello世界!