Get first word of string

Use regular expression

var totalWords = "foo love bar very much.";

var firstWord = totalWords.replace(/ .*/,'');

$('body').append(firstWord);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

I 'm using this :

function getFirstWord(str) {
        let spaceIndex = str.indexOf(' ');
        return spaceIndex === -1 ? str : str.substr(0, spaceIndex);
    };

To get first word of string you can do this:

let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
console.log(firstWord)

split(" ") will convert your string into an array of words (substrings resulted from the division of the string using space as divider) and then you can get the first word accessing the first array element with [0].

See more about the split method.


How about using underscorejs

str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )