Sasuke Kun Sasuke Kun - 2 months ago 22
Javascript Question

Get first word of string

Okey here is my code with details of what i tried to do:

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

//Now i want to get the first word of every split-ed sting parts:

for (var i=0;i<codelines.length;i++)
{
//What to do here to get the first word of every spilt
}


So what should i do there :\
What i want to get is firstword[0] will give "Hello" and firstword[1] will give "sss" and firstword[2] will give "mmm"

Answer

Split again by a whitespace:

var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
  var words = codelines[i].split(" ");
  firstWords.push(words[0]);
}

Or use String.prototype.substr() (probably faster):

var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
  var codeLine = codelines[i];
  var firstWord = codeLine.substr(0, codeLine.indexOf(" "));
  firstWords.push(firstWord);
}