variable as argument of string.match()

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mike

    #1

    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



  • Martin Honnen

    #2
    Re: variable as argument of string.match()



    Mike wrote:

    [color=blue]
    > 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.[/color]

    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/

    Comment

    Working...