Reputation: 1929
I originally used indexOf to find a space but I want to find any word boundary.
Something like this, but what regex?
var str = "This is a sentence",
firstword = str.search("");
return word;
I want to return "This". Even in the case of a tab, period, comma, etc.
Upvotes: 3
Views: 5144
Reputation: 18185
This splits the string at every word boundary and returns the first one:
var str = "This is a sentence";
firstword = str.split(/\b/)[0];
Upvotes: 3
Reputation: 41823
Something like this:
var str = "This is a sentence";
return str.split(/\b/)[0];
Although you would probably want to check that there was a match like this:
var str = "This is a sentence";
var matches = str.split(/\b/);
return matches.length > 0 ? matches[0] : "";
Upvotes: 11