Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

  • firstword[0] will give "Hello"

  • firstword[1] will give "sss"

  • firstword[2] will give "mmm"
like image 751
Sasuke Kun Avatar asked Sep 01 '13 12:09

Sasuke Kun


People also ask

How do you get one word from a string in python?

The easiest way to get the first word in string in python is to access the first element of the list which is returned by the string split() method. String split() method – The split() method splits the string into a list. The string is broken down using a specific character which is provided as an input parameter.

How can I get the first word of a string in PHP?

echo "The first word of string is: " . $arr [0]; ?> Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string.


2 Answers

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>
like image 67
Bimal Grg Avatar answered Oct 18 '22 20:10

Bimal Grg


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); } 
like image 33
ComFreek Avatar answered Oct 18 '22 19:10

ComFreek