JavaScript Splice() Method: How to Splice String in JS?

Is there a splice method for strings in JavaScript?

Well, this article will help you find the answers to this question. Just keep on reading!

This article is your go-to resource on how to splice strings in JavaScript.

Aside from that, we will show you the versatility of JavaScript with our comprehensive guide on the splice() method.

So let’s get started to learn how to modify arrays and discover techniques to achieve similar effects with strings.

What is splice() method in JavaScript?

The splice() method in JavaScript is an inbuilt function that gives you the ability to modify an array’s content.

It simply means you can modify the content of an array by removing, replacing, or adding elements.

However, this method does not work directly on strings.

If you want to manipulate a string in a similar way, you can convert the string to an array, perform the splice operation, and then join the array back into a string.

Here’s an example:


let samplestring = "Hi, Everyone!";
let arr = samplestring.split('');
arr.splice(3, 10, "Itsourcecoders!");

str = arr.join(''); 
console.log(str); 

Output:

Hi,Itsourcecoders!

Note: The full explanation you’ll see it below, so just keep on reading .😉

Syntax

Here’s the syntax for the splice() method:

array.splice(start, deleteCount, item1, item2, …, itemN) ✅

Parameters

start (Required)

The index at which to start changing the array. If negative, it will begin that many elements from the end.

deleteCount (Optional)

An integer indicating the number of elements in the array to remove from start.

item1, item2, …, itemN (Optional)

The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.

Return value

The splice() method returns an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

📌Please note that the splice() method changes the original array.

How to use splice in JavaScript

Here’s an example of using the splice() method in JavaScript:

let subjects = ["Programming", "English", "Web Development", "Math", "Software Development"];
console.log("Original array: ", subjects);

// Use splice() to remove "English" and add "Software Engineering" and "Science"
subjects.splice(1, 1, "Software Engineering", "Science"); ✅
console.log("After splice: ", subjects);

In our example, the splice() method starts at index 1 (where English is), removes 1 item (“English”), and then adds “Software Engineering” and “Science” at that location.

The modified array will be seen below:

Original array:  [
  'Programming',
  'English',
  'Web Development',
  'Math',
  'Software Development'
]


After splice:  [
  'Programming',
  'Software Engineering',
  'Science',
  'Web Development',
  'Math',
  'Software Development'
]

Remember, the splice() method modifies the original array and returns an array with the deleted items. In this case, it will return[“English”].

Different ways on how to splice string in JavaScript

Let’s get into the solutions on how to splice string in JavaScript.

As we mentioned earlier splice() method in JavaScript does not work directly on strings. It is because strings are immutable, which means they cannot be changed once created.

However, there are several ways to achieve a similar effect to the splice() method (which is used with arrays) with strings:

Solution 1: Using split(), splice(), and join() methods

let samplestring = "Hi, Everyone!";
let arr= samplestring.split('');✅   // Convert string to array

arr.splice(3, 10, ...'Itsourcoders!'); // Perform splice operation

let str= arr.join('');  // Convert array back to string
console.log(str); 

As you can see on our example code above, we first convert the string into an array using split(”).

Then, we used the splice() method to remove 10 characters starting from the 3rd index of the array (which corresponds to “, Everyone”) and replaces them with the characters from “Itsourcoders!”

Finally, join(”) is used to convert the array of characters back into a single string.

Output:

Hi,Itsourcoders!

Solution 2: Using substring() or substr() method

let samplestring = "Hi, welcome to Philippines!";
let newStr = samplestring.substring(0, 15) + "Itsourcecode"; ✅
console.log(newStr);

Here’s a step-by-step explanation:

let samplestring = "Hi, welcome to Philippines!"; 

This line declares a variable named samplestring and assigns the string “Hi, welcome to Philippines!” to it.

let newStr = samplestring.substring(0, 15) + "Itsourcecode"; 

This line does a few things:

✔ samplestring.substring(0, 15) extracts a part of samplestring from index 0 to index 14 (JavaScript indices start at 0 and the end index is exclusive). This gives us the string “Hi, welcome to “.

✔ Then it concatenates the string “Itsourcecode” to the end of this substring.

console.log(newStr); 

This line prints the value of newStr to the console.

So, if you run this code, it will print:

Output:

Hi, welcome to Itsourcecode

Essentially, it’s replacing “Philippines!” in the original string with “Itsourcecode.”

Solution 3: Using replace() method

let samplestring = "Hi, welcome to USA!";
let newStr = samplestring.replace("USA", "Itsourcecode"); ✅
console.log(newStr);

The replace() method replaces the first occurrence of a specified value with another value in a string.

Output:

Hi, welcome to Itsourcecode!

Remember that these methods do not modify the original string but return a new one.

Conclusion

In conclusion, the splice() method is a powerful tool in JavaScript that allows you to modify an array by removing, replacing, or adding elements.

Although JavaScript strings are immutable and don’t have a built-in splice() method, we can achieve similar functionality by converting the string to an array, performing the splice operation, and then converting it back to a string.

This article provided a comprehensive guide on how to use the splice() method with arrays and strings in JavaScript, complete with syntax explanations, parameter details, and practical examples.

We are hoping that this article provides you with enough information that helps you understand the JavaScript string splice.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment