5

So I am wanting to replace GET variable values in a url and if the variable does not exist, then add it to the url.

EDIT: I am doing this to a elements href not the pages current location..

I am not good with javascript but I do know how to use jQuery quite well and the basics of javascript. I do know how to write regex but not how to use the javascript syntax of regex and what functions to use it with.

Here is what I have so far and it does have an error on line 3: See it on jsfiddle(or below): http://jsfiddle.net/MadLittleMods/C93mD/

function addParameter(url, param, value) {
    var pattern = new RegExp(param + '=(.*?);', 'gi');
    return url.replace(pattern, param + '=' + value + ';');

    alert(url);
}
MLM
  • 3,530
  • 3
  • 33
  • 62

4 Answers4

15

No need to use jQuery on this one. Regular Expressions and string functions are sufficient. See my commented code below:

function addParameter(url, param, value) {
    // Using a positive lookahead (?=\=) to find the
    // given parameter, preceded by a ? or &, and followed
    // by a = with a value after than (using a non-greedy selector)
    // and then followed by a & or the end of the string
    var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))'),
        parts = url.toString().split('#'),
        url = parts[0],
        hash = parts[1]
        qstring = /\?.+$/,
        newURL = url;

    // Check if the parameter exists
    if (val.test(url))
    {
        // if it does, replace it, using the captured group
        // to determine & or ? at the beginning
        newURL = url.replace(val, '$1' + param + '=' + value);
    }
    else if (qstring.test(url))
    {
        // otherwise, if there is a query string at all
        // add the param to the end of it
        newURL = url + '&' + param + '=' + value;
    }
    else
    {
        // if there's no query string, add one
        newURL = url + '?' + param + '=' + value;
    }

    if (hash)
    {
        newURL += '#' + hash;
    }

    return newURL;
}

And here is the Fiddle

Update:

The code now handles the case where there is a hash on the URL.

Edit

Missed a case! The code now checks to see if there is a query string at all.

Ryan Kinal
  • 16,165
  • 4
  • 41
  • 63
  • 1
    Updated and added a read function to this fiddle. I used (;|&|$) instead of your (&|$) -- http://jsfiddle.net/MadLittleMods/4Pz8h/ – MLM Oct 05 '11 at 02:59
  • 1
    How about [\\?&] instead of (\\?|\\&) – Christophe Dec 23 '11 at 17:36
  • For anybody searching an alternative to this one, here's my favorite solution: http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter/11654596#11654596 – joweiser Mar 22 '13 at 11:33
  • 1
    doesn't handle hash on url – Joao Leme Jul 02 '13 at 19:34
  • It should handle the hash now. – Ryan Kinal Jul 02 '13 at 20:44
  • 1
    This code looks like a great example of why you *should* just shut up and use jQuery. Edited countless times as new bugs are randomly found, costing who knows how many developer hours, and we *still* don't even know if it actually works. jQuery is heavy because it's already been through this process. Any yahoo can "write a faster function to X" but then it doesn't work because they leave out the million corner cases that cause bugs. And we're not even yet talking about the ways that javascript *itself* makes this difficult. – John Tyree Aug 23 '14 at 17:44
  • Also, I don't see how this is in *any* way better for someone who doesn't know javascript well. It's terse and complicated even for experienced developers. – John Tyree Aug 23 '14 at 17:46
  • @JohnTyree Of course, over 3 years, I have improved my JavaScript. Now I'd just use `window.location.search.split('&')` – Ryan Kinal Aug 24 '14 at 04:37
  • what is the point of replacing the param if it already exists? – chiliNUT Feb 08 '16 at 18:56
1

I would go with this small but complete library to handle urls in js:

https://github.com/Mikhus/jsurl

Joao Leme
  • 8,945
  • 3
  • 30
  • 46
0
<script type="text/javascript">
    $(document).ready(function () {
        $('input.letter').click(function () {
            //0- prepare values
            var qsTargeted = 'letter=' + this.value; //"letter=A";
            var windowUrl = '';
            var qskey = qsTargeted.split('=')[0];
            var qsvalue = qsTargeted.split('=')[1];
            //1- get row url
            var originalURL = window.location.href;
            //2- get query string part, and url
            if (originalURL.split('?').length > 1) //qs is exists
            {
                windowUrl = originalURL.split('?')[0];
                var qs = originalURL.split('?')[1];
                //3- get list of query strings
                var qsArray = qs.split('&');
                var flag = false;
                //4- try to find query string key
                for (var i = 0; i < qsArray.length; i++) {
                    if (qsArray[i].split('=').length > 0) {
                        if (qskey == qsArray[i].split('=')[0]) {
                            //exists key
                            qsArray[i] = qskey + '=' + qsvalue;
                            flag = true;
                            break;
                        }
                    }
                }
                if (!flag)//   //5- if exists modify,else add
                {
                    qsArray.push(qsTargeted);
                }
                var finalQs = qsArray.join('&');
                //6- prepare final url
                window.location = windowUrl + '?' + finalQs;
            }
            else {
                //6- prepare final url
                //add query string
                window.location = originalURL + '?' + qsTargeted;
            }
        })
    });
</script>
Mohamed.Abdo
  • 1,420
  • 16
  • 11
0

See Change URL parameters. It answers your question in a more general manner (changing any url parameter). There are solutions for both jQuery and regular js in the answers section.

It also looks like url.replace should be location.replace but I may be wrong (that statement's based on a quick google search for 'url.replace javascript').

Community
  • 1
  • 1
jtfairbank
  • 2,251
  • 2
  • 17
  • 32
  • This is pretty close and I am guessing I need to use his new plugin called BBQ: http://benalman.com/projects/jquery-bbq-plugin/ - which is for 1.4 jquery and I am using 1.6.4 - and I am using this url(?action=expand;) My jquery would be: http://jsfiddle.net/RVCyu/ - It does not seem to be working – MLM Oct 03 '11 at 21:49
  • See http://www.netlobo.com/url_query_string_javascript.html or http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html. – jtfairbank Oct 03 '11 at 23:42
  • I am not trying to read values, I am trying to modify/add them – MLM Oct 04 '11 at 00:38