views:

136

answers:

2

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.

+4  A: 

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] : "";
Graphain
+1 same idea a little bit faster
jigfox
Only just. I rarely use JS so was happy we got the same answer.
Graphain
I thank you both
Luke Burns
+1  A: 

This splits the string at every word boundary and returns the first one:

var str = "This is a sentence";
firstword = str.split(/\b/)[0];
jigfox