View Single Post
Old 01-31-2013, 09:34 PM   PM User | #14
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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>
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote