Sometimes, we want to split string in two on given index and return both parts with JavaScript.
In this article, we’ll look at how to split string in two on given index and return both parts with JavaScript.
How to split string in two on given index and return both parts with JavaScript?
To split string in two on given index and return both parts with JavaScript, we can use the string slice method.
For instance, we write
const splitAt = (index, xs) => [xs.slice(0, index), xs.slice(index)];
console.log(splitAt(1, "foo"));
to define the splitAt function that calls xs.slice with 0 and index and with index only to return the substring between index 0 and index - 1 inclusive and from index to the end of the string inclusive.
We put both strings in an array and return it.
Then we call splitAt with the index and a string to split into 2 at index 1.
Conclusion
To split string in two on given index and return both parts with JavaScript, we can use the string slice method.