Split a String at a specific Index using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
3 min

banner

# Table of Contents

  1. Split a String at a specific Index using JavaScript
  2. Split a String at multiple indices using JavaScript

# Split a String at a specific Index using JavaScript

To split a string at a specific index:

  1. Use the slice() method to get the two parts of the string.
  2. str.slice(0, index) returns the part up to, but not including the index.
  3. str.slice(index) returns the remainder of the string.
index.js
function split(str, index) { const result = [str.slice(0, index), str.slice(index)]; return result; } const [first, second] = split('abcd', 2); console.log(first); // ๐Ÿ‘‰๏ธ "ab" console.log(second); // ๐Ÿ‘‰๏ธ "cd"

split string at specific index

The code for this article is available on GitHub

The function takes a string and an index as parameters and splits the string on the given index.

The String.slice() method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring

The first call to the slice() method gets the substring up to, but not including the provided index.

index.js
console.log('abcd'.slice(0, 2)); // ๐Ÿ‘‰๏ธ "ab"

The second call to the slice() method gets the remainder of the string.

index.js
console.log('abcd'.slice(2)); // ๐Ÿ‘‰๏ธ "cd"

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

Our split function returns an array containing the two substrings.

index.js
function split(str, index) { const result = [str.slice(0, index), str.slice(index)]; return result; } const arr = split('abcd', 2); console.log(arr); // ๐Ÿ‘‰๏ธ ['ab', 'cd']

We can use destructuring assignment to assign the substrings to variables.

index.js
function split(str, index) { const result = [str.slice(0, index), str.slice(index)]; return result; } // ๐Ÿ‘‡๏ธ destructure array elements and assign them to variables const [first, second] = split('abcd', 2); console.log(first); // ๐Ÿ‘‰๏ธ "ab" console.log(second); // ๐Ÿ‘‰๏ธ "cd"

The destructuring assignment syntax enables us to assign the array elements to the first and second variables in a single statement.

If you only have to do this once, you don't need to create a reusable function.

index.js
const str = 'abcd'; const index = 2; const first = str.slice(0, index); const second = str.slice(index); console.log(first); // ๐Ÿ‘‰๏ธ "ab" console.log(second); // ๐Ÿ‘‰๏ธ "cd"

The code sample achieves the same result but is a bit more hardcoded and simplified.

If you only have to split the string based on a provided index once or twice, it's better to avoid premature abstractions.

# Split a String at multiple indices using JavaScript

If you need to split a string at multiple indices, use this approach instead.

index.js
function split(str, ...indices) { return [0, ...indices].map((startIndex, index, arr) => { return str.slice(startIndex, arr[index + 1]); }); } // ๐Ÿ‘‡๏ธ [ 'ab', 'cd' ] console.log(split('abcd', 2)); // ๐Ÿ‘‡๏ธ [ 'ab', 'cd', 'ef' ] console.log(split('abcdef', 2, 4)); // ๐Ÿ‘‡๏ธ [ 'ab', 'cd', 'ef', 'gh' ] console.log(split('abcdefgh', 2, 4, 6));

split string at multiple indices

The code for this article is available on GitHub

The function uses the gather (...) syntax to gather the indices into an array.

The function we passed to the Array.map() method gets called with each element in the array.

The map() method returns a new array containing the values returned from the callback function.

The function we passed to the map() method gets called with 3 arguments:

  1. the current array element
  2. the current index
  3. the array that's being iterated

On each iteration, we use the String.slice() method to get a slice starting at 0 or the supplied indices and going up to the next index.

If there is no end index, the slice goes to the end of the string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev