By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,576 Members | 1,399 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,576 IT Pros & Developers. It's quick & easy.

regular expression from variable

P: n/a
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.

Martin
Aug 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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
Aug 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.