2

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"];
frederj
  • 1,483
  • 9
  • 20
Edin Puzic
  • 998
  • 2
  • 19
  • 39
  • 1
    Why don't you use ... `indexOf()` then split using a `substring()` ? – KarelG Jun 08 '17 at 12:32
  • Use split(" ",1) to get the first name and then use replace() to get the remaing string. var Name = "Jone Doe Doone"; var res1 = Name.split(" ",1); var res2 = Name.replace(res1 + " ", ""); var res = [res1, res2]; – athar13 Jun 08 '17 at 12:40

3 Answers3

1

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"));
KarelG
  • 5,176
  • 4
  • 33
  • 49
  • `const` is not yet widely supported, I doubt that he is using any transpirel. – XCS Jun 08 '17 at 12:36
  • @Cristy well ... if you check the [compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Browser_compatibility) ... it's a fair consideration. But I use that as habit. Replaced to `var` then. – KarelG Jun 08 '17 at 12:38
  • Yes, on desktop support is ok, but on mobile it's pretty bad. – XCS Jun 08 '17 at 12:44
-3

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.

-4

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);
Santhu
  • 1
  • 2