3

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.

2 Answers 2

11

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] : "";
Sign up to request clarification or add additional context in comments.

1 Comment

Only just. I rarely use JS so was happy we got the same answer.
3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.