Is there a splice method for strings?
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.
Edit
This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.
No, there is no such thing as a String.splice
, but you can try this:
newStr = str.split(''); // or newStr = [...str];
newStr.splice(2,5);
newStr = newStr.join('');
I realise there is no splice
function as in Arrays, so you have to convert the string into an array. Hard luck...
Here's a nice little Curry which lends better readability (IMHO):
The second function's signature is identical to the Array.prototype.splice
method.
function mutate(s) {
return function splice() {
var a = s.split('');
Array.prototype.splice.apply(a, arguments);
return a.join('');
};
}
mutate('101')(1, 1, '1');
I know there's already an accepted answer, but hope this is useful.