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