Reputation: 1
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?
Upvotes: 0
Views: 32
Reputation: 1075795
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.)
Upvotes: 1
Reputation: 456
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 '?'.
Upvotes: 0