SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Oct 2003
    Location
    Florida
    Posts
    264
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Having a hard time with match and regexp

    Hey everyone, here is what I'm trying to do. I'm trying to change one part of a url with something new but I can't seem to get the regexp pattern to work. I just want to match the varname, the equal sign and the number (age=21)

    HTML Code:
    <a href="#" onclick="change('age', '85');">Change AGE to 85</a>
    
    function change(varname, id)
    {				
        var url  	= "http://www.example.com/index.php?do=change&id=777&age=21";
        var newstr 	= varname + '=' + id;				
        var oldstr  = url.match(/(?=varname)\d+/)
        var newurl  = url.replace(oldstr, newstr);
        alert(newurl);
        
        // the output should have replaced the age to 85
        // http://www.example.com/index.php?do=change&id=777&age=85
    }
    I don't know how to get the varname variable inside the match correctly. Any ideas?

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    function change(varname, id)
    {
        var url      = "http://www.example.com/index.php?do=change&id=777&age=21";
        var re       = new RegExp("([?&]" + varname + "=)[^&]+");
        var newurl   = url.replace(re, "$1" + id);
        alert(newurl);
    }
    Birnam wood is come to Dunsinane

  3. #3
    SitePoint Addict
    Join Date
    Oct 2003
    Location
    Florida
    Posts
    264
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Awesome that worked! I just had to change the & to &amp; in case others use this. Thank you AutisticCuckoo!


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
  •