Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jan 2009
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Javascript regular expression problem

    Hello all,

    I am trying to write a simple javascript function that locates a parameter in a url, if it is present, and replace it with a different value. Here's my code:

    function setParam(url,param,value) {
    var a = '&'+param+'=\d+';
    var new_url = url.replace(new RegExp(a), '');
    new_url = new_url + '&'+param+'='+value;
    return new_url;
    }

    The problem is, it doesn't work. It adds the new param, value pair to the old url, but the old param isn't replaced. What do I need to do here to make this work?

    Thanks for reading.

  • #2
    New to the CF scene
    Join Date
    Jan 2009
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    clarification

    Clarification:
    If I do setParam("www.mypage.com/?p1=5&name=john","name","rob")

    I want to get the output
    www.mypage.com/?p1=5&name=rob

    instead I get

    www.mypage.com/?p1=5&name=john&name=rob

  • #3
    Regular Coder
    Join Date
    Nov 2007
    Location
    127.0.0.1
    Posts
    348
    Thanks
    26
    Thanked 40 Times in 39 Posts
    Try this:
    Code:
    function setParam(url,param,value) {
    var a = '&'+param+'.*[^&]';
    var new_value= '&'+param+"="+value;
    var new_url = url.replace(new RegExp(a),new_value);
    return new_url;
    }
    Regular expression testing can be done on http://www.quanetic.com/Regex.
    Blog Charity:Water
    WhatisWrongWith.me/tagnu - Send me anonymous feedback.


  •  

    Posting Permissions

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