Re: regular expression from variable
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: regular expression from variable

From: RobG <rgqld@iinet.net.au>
Date: Mon Aug 22 2005 - 14:13:18 CEST

Martin John Brindle wrote:
> I need to build a regular expression where the expression contents are
> variable.
>
> for example I have a string that i need to search for, but the string can
> change. If i have a variable called string I need to look at the contents of
> string otherwise
>
> /string/
>
> obviously doesn't work!
>
> Suggestions appreciated.

  function searchFor( s, str ) {
    var re = new RegExp( s );
    return re.test( str );
  }

will return true for: searchFor( 'be', 'beach')

To match a word exactly, use:

   var re = new RegExp( '\\b' + s + '\\b' );

Now:

   searchFor( 'be', 'let it be') // returns true
   searchFor( 'be', 'beat it') // returns false

To make the test case insensitive:

   var re = new RegExp( '\\b' + s + '\\b', 'i' );

etc.

-- 
Rob
Received on Mon Oct 24 02:14:18 2005