Get first word of string

JavascriptSplit

Javascript Problem Overview


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 :

  • firstword[0] will give "Hello"

  • firstword[1] will give "sss"

  • firstword[2] will give "mmm"

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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

Solution 3 - Javascript

I 'm using this :

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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(" ") )

Solution 6 - Javascript

An improvement upon previous answers (working on multi-line or tabbed strings):

String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}

Or using search and substr:

String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}

Or without regex:

String.prototype.firstWord = function(){
  let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
   filter((e)=>e!==-1);
  return sps.length? this.substr(0,Math.min(...sps)) : this;
}

Examples:

String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
console.log(`linebreak
example 1`.firstWord()); // -> linebreak
console.log('space example 2'.firstWord()); // -> singleline
console.log('tab	example 3'.firstWord()); // -> tab

Solution 7 - Javascript

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<str1.length;i++)
{
    //What to do here to get the first word :)
    var firstWord = str1[i].split(' ')[0];
    alert(firstWord);
}

Solution 8 - Javascript

This code should get you the first word,

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<str1.length;i++)
 {
     //What to do here to get the first word :(
     var words = str1[i].split(" ");
     console.log(words[0]);
 }

Solution 9 - Javascript

In modern JS, this is simplified, and you can write something like this:

const firstWords = str =>
  str .split (/\|/) .map (s => s .split (/\s+/) [0])

const str = "Hello m|sss sss|mmm ss"

console .log (firstWords (str))

We first split the string on the | and then split each string in the resulting array on any white space, keeping only the first one.

Solution 10 - Javascript

I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()


To answer the question directly:

let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");

for (var i = 0; i < codeLines.length; i++) {
  const first = codeLines[i].split(' ').shift()
  firstWords.push(first)
}

Solution 11 - Javascript

const getFirstWord = string => {
    const firstWord = [];
    for (let i = 0; i < string.length; i += 1) {
        if (string[i] === ' ') break;
        firstWord.push(string[i]);
    }
    return firstWord.join('');
};
console.log(getFirstWord('Hello World'));

or simplify it:

const getFirstWord = string => {
    const words = string.split(' ');
    return words[0];
};
console.log(getFirstWord('Hello World'));

Solution 12 - Javascript

This code should get you the first word,

const myName = 'Jahid Bhuiyan';
console.log(myName.slice(0, myName.indexOf(' ')));

Ans will be "Jahid"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSasuke KunView Question on Stackoverflow
Solution 1 - JavascriptBimal GrgView Answer on Stackoverflow
Solution 2 - JavascriptComFreekView Answer on Stackoverflow
Solution 3 - JavascriptElloneView Answer on Stackoverflow
Solution 4 - JavascriptPaulo BeloView Answer on Stackoverflow
Solution 5 - JavascriptlukaseratView Answer on Stackoverflow
Solution 6 - JavascriptCPHPythonView Answer on Stackoverflow
Solution 7 - JavascriptDiego PlutinoView Answer on Stackoverflow
Solution 8 - JavascriptrAjAView Answer on Stackoverflow
Solution 9 - JavascriptScott SauyetView Answer on Stackoverflow
Solution 10 - JavascriptWillView Answer on Stackoverflow
Solution 11 - JavascriptHossein Haji MaliView Answer on Stackoverflow
Solution 12 - Javascriptuser13026823View Answer on Stackoverflow