www.webdeveloper.com
Results 1 to 5 of 5

Thread: Referencing A Variable w/ Reg Expression..

  1. #1
    Join Date
    Sep 2008
    Posts
    260

    Referencing A Variable w/ Reg Expression..

    Just not sure how to do this, but let's say I have:

    function runIt(alpha){

    var something=alpha;
    var foo="Joe";
    var pattern=/^foo/;

    var something=something.replace(pattern, "foobear");
    }

    would the part in blue work? I want to reference a variable in a regular expression. So what would be the proper syntax for this?

  2. #2
    Join Date
    Jun 2007
    Posts
    667
    Code:
    var pattern = new RegExp( "^" + foo );

  3. #3
    Join Date
    Apr 2008
    Posts
    157
    alternatively:

    Code:
    var pattern = eval(/'^'+foo+'/gi');

    this way you don't need to worry about escaping special characters.

  4. #4
    Join Date
    Sep 2008
    Posts
    47
    Quote Originally Posted by Teufel View Post
    alternatively:

    Code:
    var pattern = eval(/'^'+foo+'/gi');

    this way you don't need to worry about escaping special characters.
    So taking your advice towards this post, if I'm trying to replace the a in

    Code:
    <span class="whatever">M</span>axwell
    with <span class="whatever">a</span> to produce,
    Code:
    <span class="whatever">M</span><span class="whatever">a</span>xwell
    I could target '>a' using a regular expression. So let's say that:

    Code:
    var the_letter=alpha;
    var exp=/^>+the_letter+$/;
    Couldn't this be the appropriate regular expression?

  5. #5
    Join Date
    Aug 2007
    Posts
    3,767
    Quote Originally Posted by JohnBeason View Post
    Code:
    var the_letter=alpha;
    var exp=/^>+the_letter+$/;
    Couldn't this be the appropriate regular expression?
    No, either
    Code:
    var exp = new RegExp(">"+the_letter, "ig");
    Or, the one I wouldn't use would be
    Code:
    var exp = eval("/>"+the_letter+"/ig;");
    The ig in both examples is optional, I'm just putting it there so you know where they go for either example.

    ^ and $ mean at the start of the string, so /^>a$/ would only match the string ">a", and not "anything at all>aanything at all".
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles