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.
The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract. The first position is 0, the second is 1, ...
The splice() method returns the removed items in an array. The slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.
The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.
The slice() is an inbuilt function in TypeScript which is used to extracts a section of a string and returns a new string. Parameter: This method accept two parameter as mentioned above and described below: beginSlice – This parameter is the zero-based index at which to begin extraction.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With