Split string on the first white space occurrence
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.substring(0, str.indexOf(' ')); // "72"
str.substring(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).
In ES6 you can also
let [first, ...second] = str.split(" ")
second = second.join(" ")
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)