javascriptsplit

Get first word of string


Okay, here is my code with details of what I have 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 :


Solution

  • 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);
    }