Here's a slightly better version. Handles the sentence *before* "happy" ending with ? or ! (not just period).
Has the interesting effect of changing *which* "happy" is found in demo #5. If you really wanted the first one found, I could fix it to do that. But I'm assuming that's a case you aren't too worried about.
Code:
<script>
function findSentenceByWord( text, word )
{
var re1 = new RegExp( "[A-Z\\.\\?\\!][^A-Z\\.\\?\\!]+?" + word + "[^\\.\\?\\!]*[\\.\\?\\!]", "" );
var re2 = new RegExp( "^[\\s\\S]*?" + word + "[^\\.\\?\\!]*[\\.\\?\\!]", "" );
var re3 = new RegExp( "[A-Z\\.\\?\\!][^A-Z\\.\\?\\!]+?" + word + "[\\s\\S]*$", "" );
var re4 = new RegExp( "^[\\s\\S]*?" + word + "[\\s\\S]*$", "" );
var res = [ re1, re2, re3, re4 ];
for ( var r = 0; r < res.length; ++r )
{
var re = res[r];
if ( re.test( text ) )
{
document.write("Match on regexp " + (r+1) + "<br/>");
var m = text.match(re)[0];
m = m.replace( /^[\.\?\!]?\s*/, "" );
document.write( m + "<br/>");
return;
}
}
}
function demo( text, word )
{
document.write( "<hr/>Testing <i><b>" + text + "</b></i> for word " + word + "<br/>" );
findSentenceByWord( text, word );
}
demo( "The dog jumped over the moon. He was happy to see me. I left in a hurry", "happy" );
demo( "was happy to see me. I left in a hurry", "happy" );
demo( "The dog jumped over the moon. He was happy to see", "happy" );
demo( "aardvarks whistle. happy dogs bark", "happy" );
demo( "aardvarks whistle dixie! happy dogs bark", "happy" );
demo( "happy happy happy! and even more happy?", "happy" );
demo( "all the happy dogs", "happy" );
</script>