Sometimes, we want to split string on the first white space occurrence with JavaScript.
In this article, we’ll look at how to split string on the first white space occurrence with JavaScript.
How to split string on the first white space occurrence with JavaScript?
To split string on the first white space occurrence with JavaScript, we call string’s match method with a regex that match all whitespace characters that comes before other characters.
For instance, we write
const matches = str.match(/^(\S+)\s(.*)/).slice(1);
to call match with /^(\S+)\s(.*)/ to return an array with all the strings whitespace strings that comes after whitespaces.
And then we can get the non-whitespace substring that comes after the first whitespace substring by calling slice with 1.
Conclusion
To split string on the first white space occurrence with JavaScript, we call string’s match method with a regex that match all whitespace characters that comes before other characters.