469,934 Members | 2,589 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,934 developers. It's quick & easy.

regular expression from variable

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
1 1641
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.

Similar topics

6 posts views Thread by Chris Lasher | last post: by
5 posts views Thread by Bradley Plett | last post: by
2 posts views Thread by Brian Kitt | last post: by
7 posts views Thread by Billa | last post: by
3 posts views Thread by LordHog | last post: by
25 posts views Thread by Mike | last post: by
3 posts views Thread by Mr.Steskal | last post: by
1 post views Thread by NvrBst | last post: by
1 post views Thread by Shawn B. | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.