Sylar
Sylar

Reputation: 12072

How To Get First Word In The String

Answers on the web relates to other programming languages. I have done many searches but none seems to work. I'm looking for per title.

var str = ["bob, b", "the, d", "builder, e", "can", "he", "fix", "it" ]
str.match(/^(\w+)/) // Uncaught TypeError: str.match is not a function

I have tried to look at this but....I'm still learning and my not be using it correctly.

How do I return only bob and not bob, b?

Upvotes: 1

Views: 5304

Answers (6)

Surender Lohia
Surender Lohia

Reputation: 379

Try this...

function getFirstWord(str) {
  var matched = str.match(/^\w+/);
  if(matched) {
    return matched[0];
  }

  console.error("No Word found");
  return -1;
};

var str = ["bob, b", "the, d", "builder, e", "can", "he", "fix", "it"];

for(var i = 0, strLen = str.length; i < strLen; i += 1) {
  var item = str[i];
  var firstWord = getFirstWord(item);

  console.log(firstWord);
}

Upvotes: 0

user2510356
user2510356

Reputation: 11

Hey first you need to get the 0th element from the array and then split it with coma so that it will return you an array, once you get the array you can extract the first element out of it.

In a nut shell the following works

var str = ["bob, b", "the, d", "builder, e", "can", "he", "fix", "it" ]

console.log(str[0].split(',')[0]);

Upvotes: -1

Mi-Creativity
Mi-Creativity

Reputation: 9654

JS Fiddle

var str = ["bob, b", "the, d", "builder, e", "can", "he", "fix", "it" ];
for(var i=0; i < str.length; ++i){
    console.log(str[i].match('[a-zA-Z]+'));
}

Upvotes: 3

Code Different
Code Different

Reputation: 93161

You can't apply regex on an array. Iterate over each element:

/(\w+)/.exec(str[i])[1]

JSFiddle

Upvotes: -1

TheHans255
TheHans255

Reputation: 2223

You're running match() not on the string, but on an array of strings. str is an array (and thus has no idea what's inside it), but str[0], the first element of that array, is a String and has a match() method. Run the Regex on str[0] and you should get back "bob".

And it would be good to rename your array variable to reflect this (e.g. strArray).

Upvotes: 0

naurel
naurel

Reputation: 625

About your regex :

First you have to look at the beginning of the string with ^.

Then you want to match letters (or number ?) as long as there isn't any other char :

[a-zA-Z0-9]

Your regex should be something like

^[a-zA-Z0-9]+

And as @Compynerd255 said : you need to apply your match() function on your strings and not your array.

Upvotes: 0

Related Questions