views:

121

answers:

3

I am trying to write a regular expression in javascript for finding if any words in a sentence start with a particular phrase. Eg, I'd like to know if "by" is contained at the beginning of any word in the following sentence : "The Tipping Point by Malcolm Gladwell".

I tried using \b but /\bsor/ will match a sentence like 'Mary's organ is broken.' ie it treats punctuation as a word boundary and starts matching after them. Any thoughts?

A: 

How about using split on the sentence to try your expression on every word?

You could also use indexOf rather than a regexp.

Aif
+1  A: 

/(?:\s|^)bar/ -- perhaps -- although see the answer for splitting it first

/(?:\s|^)bar/.test("bar")     // true
/(?:\s|^)bar/.test("foo bar") // true
/(?:\s|^)bar/.test("foo'bar") // false
/(?:\s|^)bar/.test("Sentence One.bar Two.") // false ... "oops"?
pst
A: 

On Regexpedia, there is an article has the code and explainations.

JavaScript Search for Lines Beginning with a Word

Shi Chuan