Split a String at a specific Index using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Split a String at a specific Index using JavaScript #

To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str.slice(0, index) returns the part of the string up to, but not including the provided index, and 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"

We created a reusable function that takes a string and an index as parameters.

We used the String.slice method to split the string based on the provided index.

We called the method with the following arguments:

  1. start index - the index of the first character to be included in the string
  2. end index - go up to, but not including this index

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 passed a single argument, the slice method starts at the provided index and includes the characters 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 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 values in the array 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.

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.