470,647 Members | 1,369 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

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

variable as argument of string.match()

Hello.

Is it possible to specify a variable instead of a string as argument of
string.match().

Example :

myString.match(/abc/i) works but how to do this :

pattern = "abc"

and then

myString.match(???)

to get the same result.

Thanks beforehand.

Mike

Jul 23 '05 #1
1 2589


Mike wrote:

Is it possible to specify a variable instead of a string as argument of
string.match().

Example :

myString.match(/abc/i) works but how to do this :

pattern = "abc"

and then

myString.match(???)

to get the same result.


Use the RegExp constructor

var s = "abc";
alert("abcdefg".match(new RegExp(s, "i")))
but be aware the you might need to double escape backslashes e.g. if
your regular expression literal is
var pattern = /\r/
you need
var pattern = new RegExp("\\r")
--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Consuelo Guenther | last post: by
134 posts views Thread by James A. Donald | last post: by
17 posts views Thread by ethan | last post: by
5 posts views Thread by shaanxxx | last post: by
6 posts views Thread by CptDondo | last post: by
reply views Thread by warner | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.