Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding/Modify query string / GET variables in a url with javascript

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);
}
like image 968
MLM Avatar asked Oct 03 '11 20:10

MLM


People also ask

Is there a way to pass javascript variables in URL?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.

How can I append a query parameter to an existing URL?

This can be done by using the java. net. URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax. The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.

How do you query parameters in a URL?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

How do you assign a variable to a URL?

Supported Syntax To insert a variable to a URL, use the @ symbol followed by the variable name: @VarName.


2 Answers

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.

like image 58
Ryan Kinal Avatar answered Nov 14 '22 23:11

Ryan Kinal


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

https://github.com/Mikhus/jsurl

like image 20
Joao Leme Avatar answered Nov 14 '22 23:11

Joao Leme