SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2006
    Posts
    87
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Grouped regEx replacement with variable?

    I have searched and searched and tried many different options but can not get this to work although I am sure it is possible.

    I need to be able to replace a string using a variable as the search and replacing using the matched reference group such as $1

    I can search for a variable and I can get the reference to work - but not both at the same time.

    The following works great - except it does not preserve the case of "Test" in the string

    Code JavaScript:
    var q = "test".toLowerCase();
    var mystring = "My Test string";
    var reg = new RegExp(q, "i");
    mystring.replace(reg, "<mark>"+q+"</mark>");

    This is the reason I can not simple replace with "q" and need to replace with what was actually found. But this does not work like this:


    Code JavaScript:
    var q = "test".toLowerCase();
    var mystring = "My Test string";
    var reg = new RegExp((q), "i");
    mystring.replace(reg, "<mark>$1</mark>");

    I guess the question is: As "q" is a variable - how do I put parentheses around it so that I can reference it in the replace statement?
    Soren Beck Jensen

    http://www.automaticbacklinks.com - Free link exchange network
    http://www.notwebdesign.com - Joomla web design in Spain

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    The $1 provides the first captured string. You have not yet specified any captured group in your regular expression. You do that with parenthesis in your regex

    For example:

    Code javascript:
    var reg = new RegExp('(' + q + ')', "i");
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Tags for this Thread

Bookmarks

Posting Permissions

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