How to Split a String at a Provided Index in JavaScript

avatar

Borislav Hadzhiev

Tue Nov 16 20212 min read

Split a String at a Provided Index #

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 the string and the index as parameters.

To split the string based on the provided index, we used the String.slice method, passing it the following parameters:

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

Our 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 parameter, the slice method starts at the provided index and includes the characters to the end of the string.

Our implementation of the split method 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 allows us to assign the values of the array to the first and second variables, using a single statement.

If you only have to do this once, it's an overkill to create a reusable function, you can call the slice method twice and assign the results to a variable.
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"

This code snippet achieves the same result, however 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee