How to Splice String in JavaScript

Anika Tabassum Era Feb 02, 2024
  1. Use splice() Method With the split() Method in JavaScript
  2. Use splice() Method With Spread Operator in JavaScript
How to Splice String in JavaScript

JavaScript has a similar method as splice() that only lets accessing the element as an array. This method is slice(), and this doesn’t perform anything other than accessing the string characters.

The splice() effortlessly takes an argument for locating the index to be altered or removed and has a count parameter that says how many characters will be removed.

Finally, a parameter that takes a string or number will be reallocated in the removal position. Here, we will see two examples of the splice() method.

One will be splitting a string into an array using the split() method. Another would be an example with the spread operator.

Use splice() Method With the split() Method in JavaScript

We will split the string as an array in the following example with the split() method.

Here, the splice() method will take index, count, and add arguments.

function spliceSplit(str, index, count, add) {
  var array = str.split('');
  array.splice(index, count, add);
  return array.join('');
}
console.log(spliceSplit('I love you 3000', 11, 4, 42));

Output:

Use splice() Method Along with the split() Method

As you can see, the index parameter points to the 11th index, and the count argument defines how many characters are to be removed.

The add parameter will be set at the 11th index, and it is an optional case, so if you haven’t added it, the splice() method will only remove characters based on index and count.

Use splice() Method With Spread Operator in JavaScript

We will initiate a new object and store our string in an array form for this case. We will use the spread operator here to convert the string to an array.

The rest of the mechanism of the splice() method plays the same role. In the first example, we added a number, and here we will add a string.

var str = 'I\'m a happy soul in a happy world';
var len = str.length;
console.log(len);
var newStr = [...str];
newStr.splice(6, 5, 'sad');
newStr = newStr.join('');
console.log(newStr);

Output:

Use splice() Method with Spread Operator

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript String