0

I want to change any parameter is available from a URL using Javascript

Ex: http://demo.com/admin/?admin-page=faq&kw=123 => http://demo.com/admin/?admin-page=faq&kw=123456

I have tried several ways but have not achieved the desired results you can help me solve it?

1
  • 1
    "I have tried several ways" Like what? "...but have not achieved the desired results." In what way? What happened instead of what you expected? Commented Mar 20, 2014 at 7:17

2 Answers 2

1

The portion of the URL you're changing is the query string, which is available from the location.search property. It's a &-separated series of URI-encoded key=value pairs.

You can split it up like this:

var search = location.search.charAt(0) === '?' ? location.search.substring(1) : location.search;
var pairs = search.split('&').map(function(pair) {
    return pair.split('=');
});

Then search through pairs looking for the one where pair[0] is kw and replace its value:

pairs.some(function(pair) {
    if (pair[0] === 'kw') {
        pair[1] = encodeURIComponent(yourNewValue);
        return true;
    }
});

(Array#some loops through the entries of an array and stops when you return true from the callback.)

Then assign the result:

location.search = '?' + pairs.join('&');

...which will load the page with the new query string in the window.


Side note: The above uses two features of arrays that are new as of ES5. Both are "shimmable" so if you need to support IE8, you'll want an ES5 shim. (Searching for "es5 shim" will give you options.)

Sign up to request clarification or add additional context in comments.

2 Comments

FYI - I tried your map code array[index] = pair.split('=');, but this did not work for me (Chrome v33), since pairs[0] and pairs[1] were set to undefined. Instead I had to use return pair.split('='); which did the trick.
@JasonEvans: Ah, yes, I did a combination of two things there. Either use map and return the split, or use forEach (and create the array separately). Was typing too fast. Fixed.
0

So if i understand correctly, you just want to update an URL. Then you just have to edit it.

With jQuery :

$("#myLink").attr("href", myNewHref);

Pure Javascript :

myLink.href = myNewHref;

Where myNewHref can be update using string manipulation such split function or Regex to get the first part of your URL (http://demo.com/admin/) and then getting parameters after the character '?'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.