How to add parameters to a URL that already contains other parameters and maybe an anchor
I'm wondering how I can add a new parameter to an existing url. The problem is: the url may also contain an anchor.
For example:
http://www.example.com?foo=bar开发者_StackOverflow#hashme
And I want to add another parameter to it, so it results in this:
http://www.example.com?foo=bar&x=y#hashme
I used parts of The Awesome One's solution, and a solution found on this question:
Adding a parameter to the URL with JavaScript
Combining them into this script:
function addParameter(url, parameterName, parameterValue, atStart/*Add param before others*/){
replaceDuplicates = true;
if(url.indexOf('#') > 0){
var cl = url.indexOf('#');
urlhash = url.substring(url.indexOf('#'),url.length);
} else {
urlhash = '';
cl = url.length;
}
sourceUrl = url.substring(0,cl);
var urlParts = sourceUrl.split("?");
var newQueryString = "";
if (urlParts.length > 1)
{
var parameters = urlParts[1].split("&");
for (var i=0; (i < parameters.length); i++)
{
var parameterParts = parameters[i].split("=");
if (!(replaceDuplicates && parameterParts[0] == parameterName))
{
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterParts[0] + "=" + (parameterParts[1]?parameterParts[1]:'');
}
}
}
if (newQueryString == "")
newQueryString = "?";
if(atStart){
newQueryString = '?'+ parameterName + "=" + parameterValue + (newQueryString.length>1?'&'+newQueryString.substring(1):'');
} else {
if (newQueryString !== "" && newQueryString != '?')
newQueryString += "&";
newQueryString += parameterName + "=" + (parameterValue?parameterValue:'');
}
return urlParts[0] + newQueryString + urlhash;
};
Example: addParameter('http://www.example.com?foo=bar#hashme', 'bla', 'valuebla', false)
Results in http://www.example.com?foo=bar&bla=valuebla#hashme
This can be another good solution, this version is even able to replace the parameter if it already exists, add parameter without value:
function addParam(url, param, value) {
var a = document.createElement('a'), regex = /(?:\?|&|&)+([^=]+)(?:=([^&]*))*/g;
var match, str = []; a.href = url; param = encodeURIComponent(param);
while (match = regex.exec(a.search))
if (param != match[1]) str.push(match[1]+(match[2]?"="+match[2]:""));
str.push(param+(value?"="+ encodeURIComponent(value):""));
a.search = str.join("&");
return a.href;
}
url = "http://www.example.com#hashme";
newurl = addParam(url, "ciao", "1");
alert(newurl);
http://jsfiddle.net/bknE4/81/
Try this:
location.href = location.href.replace(location.hash, '') + '&x=y' + location.hash
Update
What about this:
var a = document.createElement('a');
a.href = "http://www.example.com?foo=bar#hashme";
var url = a.href.replace(a.hash, '') + '&x=y' + a.hash;
I found out that the location object can be created by an anchor element(from Creating a new Location object in javascript).
You can use this JS lib called URI.JS
// mutating URLs
URI("http://example.org/foo.html?hello=world")
.username("rodneyrehm")
// -> http://rodneyrehm@example.org/foo.html?hello=world
.username("")
// -> http://example.org/foo.html?hello=world
.directory("bar")
// -> http://example.org/bar/foo.html?hello=world
.suffix("xml")
// -> http://example.org/bar/foo.xml?hello=world
.hash("hackernews")
// -> http://example.org/bar/foo.xml?hello=world#hackernews
.fragment("")
// -> http://example.org/bar/foo.xml?hello=world
.search("") // alias of .query()
// -> http://example.org/bar/foo.xml
.tld("com")
// -> http://example.com/bar/foo.xml
.search({ foo: "bar", hello: ["world", "mars"] });
// -> http://example.com/bar/foo.xml?foo=bar&hello=world&hello=mars
or
URI("?hello=world")
.addSearch("hello", "mars")
// -> ?hello=world&hello=mars
.addSearch({ foo: ["bar", "baz"] })
// -> ?hello=world&hello=mars&foo=bar&foo=baz
.removeSearch("hello", "mars")
// -> ?hello=world&foo=bar&foo=baz
.removeSearch("foo")
// -> ?hello=world
Easy.
<script>
function addPar(URL,param,value){
var url = URL;
var hash = url.indexOf('#');
if(hash==-1)hash=url.length;
var partOne = url.substring(0,hash);
var partTwo = url.substring(hash,url.length);
var newURL = partOne+'&'+param+'='+value+partTwo
return newURL;
}
document.write(addPar('http://www.example.com?foo=bar','x','y')) // returns what you asked for
</script>
The code could be modified a bit, and made a little more efficient, but this should work fine.
@Sangol's solution's better. Didn't know a location.hash property existed.
@freedev answer is great, but if you need something very simple (to insert key=value pair to the url and assume that key doesn't already exist), there's a much faster way to do it:
var addSearchParam = function(url,keyEqualsValue) {
var parts=url.split('#');
parts[0]=parts[0]+(( parts[0].indexOf('?') !== -1) ? '&' : '?')+keyEqualsValue;
return parts.join('#');
}
Example usage: addSearchParam('http://localhost?a=1#hash','b=5');
Here is an improved version of the answer by @skerit. This one supports #
in URL path.
function addParameter(url, parameterName, parameterValue, atStart/*Add param before others*/) {
var replaceDuplicates = true;
var cl, urlhash;
parameterName = encodeURIComponent(parameterName);
parameterValue = encodeURIComponent(parameterValue);
if (url.lastIndexOf('#') > 0) {
cl = url.lastIndexOf('#');
urlhash = url.substring(cl, url.length);
} else {
urlhash = '';
cl = url.length;
}
var sourceUrl = url.substring(0, cl);
var urlParts = sourceUrl.split("?");
var newQueryString = "";
if (urlParts.length > 1) {
var parameters = urlParts[1].split("&");
for (var i=0; (i < parameters.length); i++) {
var parameterParts = parameters[i].split("=");
if (!(replaceDuplicates && parameterParts[0] === parameterName)) {
if (newQueryString === "") {
newQueryString = "?";
} else {
newQueryString += "&";
}
newQueryString += parameterParts[0] + "=" + (parameterParts[1]?parameterParts[1]:'');
}
}
}
if (newQueryString === "") {
newQueryString = "?";
}
if (atStart) {
newQueryString = '?'+ parameterName + "=" + parameterValue + (newQueryString.length>1?'&'+newQueryString.substring(1):'');
} else {
if (newQueryString !== "" && newQueryString != '?') {
newQueryString += "&";
}
newQueryString += parameterName + "=" + (parameterValue?parameterValue:'');
}
return urlParts[0] + newQueryString + urlhash;
}
Examples:
addParameter('http://www.example.com?foo=bar#hashme', 'bla', 'valuebla', false);
// Returns: http://www.example.com?foo=bar&bla=valuebla#hashme
addParameter('http://www.example.com/#iAmNotUrlHash/?foo=bar#hashme', 'bla', 'valuebla', false);
// Returns: http://www.example.com/#iAmNotUrlHash/?foo=bar&bla=valuebla#hashme
Something like this ?
var param = "x=y";
var split = url.split('#');
url = split[0] + '&' + param + "#" + split[1];
I always use this code, and its working fine ...
var currenturl=location.href;
var url = location.href+"?ts="+true;
window.location.replace(url,"_self");
if you are trying to add to the url parameter by html anchor tag, and, you have something like this just like I do:
<div class="wrapper-option">
<a href="?tab=js">JS</a>
<a href="?tab=css">CSS</a>
<a href="?seq=popularity">popular</a>
<a href="?seq=new">newest</a>
</div>
you can do something like:
// anchor setup
const anchors = this.document.querySelectorAll('.wrapper-option a');
anchors.forEach(a=>{
a.onclick = e => {
e.preventDefault();
if(a.href){
let uri = new URL(a.href);
let url = new URL(window.location.href);
for(const [k, v] of uri.searchParams){
url.searchParams.set(k, v);
}
window.location.href = url.href;
}
}
});
this will add param to url if it does exist, rewrite if exist. and will not allow duplicate and list.
精彩评论