I didn't get an optimized regex that split me a String basing into the first white space occurrence:
var str="72 tocirah sneab";
I need to get:
[
"72",
"tocirah sneab",
]
I didn't get an optimized regex that split me a String basing into the first white space occurrence:
var str="72 tocirah sneab";
I need to get:
[
"72",
"tocirah sneab",
]
If you only care about the space character (and not tabs or other whitespace characters) and only care about everything before the first space and everything after the first space, you can do it without a regular expression like this:
str.substr(0,str.indexOf(' ')); // "72"
str.substr(str.indexOf(' ')+1); // "tocirah sneab"
Note that if there is no space at all, then the first line will return an empty string and the second line will return the entire string. Be sure that is the behavior that you want in that situation (or that that situation will not arise).
Somewhat pedantic update: Although it is supported in effectively all browsers as well as Node.js, deno, etc., String.prototype.substr() has never been added normatively to the ECMAScript spec. Practically, this is unlikely to affect you. However, if it bothers you (or if you are running in some resource-constrained environment that doesn't have String.prototype.substr() for some reason), you can use one of the many other fine answers people have provided on this question. String.prototype.slice() is a pretty good substitute but be careful of the weirdness that ensues if indexOf() returns -1 for the second argument to slice(). (It will truncate the last character of the string.) Personally, I like the regexp lookbehind solution at the end of @georg's answer, but that won't work for very old browsers, so be aware of that.
Javascript doesn't support lookbehinds, so split is not possible. match works:
str.match(/^(\S+)\s(.*)/).slice(1)
Another trick:
str.replace(/\s+/, '\x01').split('\x01')
how about:
[str.replace(/\s.*/, ''), str.replace(/\S+\s/, '')]
and why not
reverse = function (s) { return s.split('').reverse().join('') }
reverse(str).split(/\s(?=\S+$)/).reverse().map(reverse)
or maybe
re = /^\S+\s|.*/g;
[].concat.call(re.exec(str), re.exec(str))
2019 update: as of ES2018, lookbehinds are supported:
str = "72 tocirah sneab"
s = str.split(/(?<=^\S+)\s/)
console.log(s)
georg's solution is nice, but breaks if the string doesn't contain any whitespace. If your strings have a chance of not containing whitespace, it's safer to use .split and capturing groups like so:
str_1 = str.split(/\s(.+)/)[0]; //everything before the first space
str_2 = str.split(/\s(.+)/)[1]; //everything after the first space
I'm not sure why all other answers are so complicated, when you can do it all in one line, handling the lack of space as well.
As an example, let's get the first and "rest" components of a name:
const [first, rest] = 'John Von Doe'.split(/\s+(.*)/);
console.log({ first, rest });
// As array
const components = 'Surma'.split(/\s+(.*)/);
console.log(components);
Just split the string into an array and glue the parts you need together. This approach is very flexible, it works in many situations and it is easy to reason about. Plus you only need one function call.
arr = str.split(' '); // ["72", "tocirah", "sneab"]
strA = arr[0]; // "72"
strB = arr[1] + ' ' + arr[2]; // "tocirah sneab"
Alternatively, if you want to cherry-pick what you need directly from the string you could do something like this:
strA = str.split(' ')[0]; // "72";
strB = str.slice(strA.length + 1); // "tocirah sneab"
Or like this:
strA = str.split(' ')[0]; // "72";
strB = str.split(' ').splice(1).join(' '); // "tocirah sneab"
However I suggest the first example.
Working demo: jsbin
Whenever I need to get a class from a list of classes or a part of a class name or id, I always use split() then either get it specifically with the array index or, most often in my case, pop() to get the last element or shift() to get the first.
This example gets the div's classes "gallery_148 ui-sortable" and returns the gallery id 148.
var galleryClass = $(this).parent().prop("class"); // = gallery_148 ui-sortable
var galleryID = galleryClass.split(" ").shift(); // = gallery_148
galleryID = galleryID.split("_").pop(); // = 148
//or
galleryID = galleryID.substring(8); // = 148 also, but less versatile
I'm sure it could be compacted into less lines but I left it expanded for readability.
I needed a slightly different result.
I wanted the first word, and what ever came after it - even if it was blank.
str.substr(0, text.indexOf(' ') == -1 ? text.length : text.indexOf(' '));
str.substr(text.indexOf(' ') == -1 ? text.length : text.indexOf(' ') + 1);
so if the input is oneword you get oneword and ''.
If the input is one word and some more you get one and word and some more.
Most of the answers above search by space, not whitespace. @georg's answer is good. I have a slightly different version.
s.trim().split(/\s(.*)/).splice(0,2)
I'm not sure how to tell which is most efficient as the regexp in mine is a lot simpler, but it has the extra splace.
(@georg's for reference is s.split(/(?<=^\S+)\s/))
The question doesn't specify how to handle no whitespace or all whitespace, leading or trailing whitespace or an empty string, and our results differ subtly in those cases.
I'm writing this for a parser that needs to consume the next word, so I prefer my definition, though @georg's may be better for other use cases.
input. mine @georg
'aaa bbb' ['aaa','bbb'] ['aaa','bbb']
'aaa bbb ccc' ['aaa','bbb ccc'] ['aaa','bbb ccc']
'aaa ' [ 'aaa' ] [ 'aaa', '' ]
' ' [ '' ] [ ' ' ]
'' [''] ['']
' aaa' ['aaa'] [' aaa']
The following function will always split the sentence into 2 elements. The first element will contain only the first word and the second element will contain all the other words (or it will be a empty string).
var arr1 = split_on_first_word("72 tocirah sneab"); // Result: ["72", "tocirah sneab"]
var arr2 = split_on_first_word(" 72 tocirah sneab "); // Result: ["72", "tocirah sneab"]
var arr3 = split_on_first_word("72"); // Result: ["72", ""]
var arr4 = split_on_first_word(""); // Result: ["", ""]
function split_on_first_word(str)
{
str = str.trim(); // Clean string by removing beginning and ending spaces.
var arr = [];
var pos = str.indexOf(' '); // Find position of first space
if ( pos === -1 ) {
// No space found
arr.push(str); // First word (or empty)
arr.push(''); // Empty (no next words)
} else {
// Split on first space
arr.push(str.substr(0,pos)); // First word
arr.push(str.substr(pos+1).trim()); // Next words
}
return arr;
}