I want to split string in array based just on first white space in string.
Like this:
var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];
I want to split string in array based just on first white space in string.
Like this:
var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];
Here is an example where I have used indexOf()
to find the first space and then return with a splitted array with substring()
function splitAtFirstSpace(str) {
if (! str) return [];
var i = str.indexOf(' ');
if (i > 0) {
return [str.substring(0, i), str.substring(i + 1)];
}
else return [str];
}
console.log(splitAtFirstSpace("Jone Doe Doone"));
console.log(splitAtFirstSpace("BooDoone"));
console.log(splitAtFirstSpace("Doe Doone"));
Simple.
function splitFirst(s) {
var firstW = s.indexOf(" ");
if (firstW < 0) {
return s;
}
var array = [];
array.push(s.substring(0, firstW));
array.push(s.substring(firstW, s.length - 1));
return array;
}
Note: Javascript coding convention says variables have to start with lowercase.
Try the following answer.
var Name = "Jone Doe Doone";
var result = [Name.split(" ")[0]];
result.push(Name.substr(Name.split(" ")[0].length).trim());
console.log(result);