Related
While using some code to get an image url, I have ran into some issues, the code is saying url.match is not a function.
Any help would be great!
function youtube(url = $w('#input1')) {
var regExp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[1].length === 11) {
let urllink = match[1];
let imagelink = "http:\/\/img.youtube.com\/vi\/" + urllink + "\/hqdefault.jpg\"";
console.log(imagelink);
} else {
//Nothing
}
}
Thanks
According to wix documentation, $w function selects and returns elements from a page.
If you have an input on the page with id set to input1 (you are trying to select it by calling $w('#input1')) than the variable url holds handle for the input, not the value of the input.
So try to get the value from it (like url = url.value, or just url = $w('#input1').value), and after than call url.match(regExp);.
Edit your function like this:
function youtube(url = $w('#input1')) {
var regExp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
url = url.value;
var match = url.match(regExp);
if (match && match[1].length === 11) {
let urllink = match[1];
let imagelink = "http:\/\/img.youtube.com\/vi\/" + urllink + "\/hqdefault.jpg\"";
console.log(imagelink);
}
else {
//Nothing
}
}
I am getting problem in removing query string arrays from the URL.
This is my URL -
In Chrome, it displays in the given format -
Var url = "http://mywebsite.com/innovation?agenda%5B%5D=4995&agenda%5B%5D=4993#ideaResult";
Whereas, in mozilla it displays in this format -
http://mywebsite.com/innovation?agenda[]=4995&agenda[]=4993#ideaResult
I want to remove the particular query paramter.
Suppose I want to remove "4995" then final URL should supposed to be like this-
http://mywebsite.com/innovation?agenda[]=4993#ideaResult
Please help.
function removeArrayParam(key, value, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("[]=")[0];
paramValue = params_arr[i].split("[]=")[1];
if (param === key && paramValue === value) {
params_arr.splice(i, 1);
}
}
if(params_arr.length) {
rtn = rtn + "?" + params_arr.join("&");
}
}
return rtn;
}
This function will give you the desired result. Just pass key, value and the hashless url.
var url = window.location.href;
var hash = window.location.hash;
var index_of_hash = url.indexOf(hash) || url.length;
var hashless_url = url.substr(0, index_of_hash);
var desired_url = removeArrayParam(key, value, unescape(hashless_url));
what about replace() function?
var url = " http://mywebsite.com/innovation?agenda[]=4995&agenda[]=4993#ideaResult";
url = url.replace('agenda%5B%5D=4995&', '')
url = url.replace('agenda[]=4995&', '')
You can decode the url to make it consistent
ie.
var url = decodeURI("http://mywebsite.com/innovation?agenda%5B%5D=4995&agenda%5B%5D=4993#ideaResult");
....and then split the string and remove a query string. Theres an example in this question here Remove querystring from URL
The decodeURI() function according to Mozilla document:
Replaces each escape sequence in the encoded URI with the character
that it represents
So you can use it like below:
decodeURI(window.location).replace(/agenda\[\]=4995&?/,'')
Been searching for ages for a non-plugin solution to removing arrays and non-arrays from query strings, and then re-adding. It could maybe be a bit more elegant, but this works very well with all of my test cases.
function removeURLParameter(param, url) {
url = decodeURI(url).split("?");
path = url.length == 1 ? "" : url[1];
path = path.replace(new RegExp("&?"+param+"\\[\\d*\\]=[\\w]+", "g"), "");
path = path.replace(new RegExp("&?"+param+"=[\\w]+", "g"), "");
path = path.replace(/^&/, "");
return url[0] + (path.length
? "?" + path
: "");
}
function addURLParameter(param, val, url) {
if(typeof val === "object") {
// recursively add in array structure
if(val.length) {
return addURLParameter(
param + "[]",
val.splice(-1, 1)[0],
addURLParameter(param, val, url)
)
} else {
return url;
}
} else {
url = decodeURI(url).split("?");
path = url.length == 1 ? "" : url[1];
path += path.length
? "&"
: "";
path += decodeURI(param + "=" + val);
return url[0] + "?" + path;
}
}
How to use it:
url = location.href;
-> http://example.com/?tags[]=single&tags[]=promo&sold=1
url = removeURLParameter("sold", url)
-> http://example.com/?tags[]=single&tags[]=promo
url = removeURLParameter("tags", url)
-> http://example.com/
url = addURLParameter("tags", ["single", "promo"], url)
-> http://example.com/?tags[]=single&tags[]=promo
url = addURLParameter("sold", 1, url)
-> http://example.com/?tags[]=single&tags[]=promo&sold=1
Of course, to update a parameter, just remove then add. Feel free to make a dummy function for it.
Im giving my users the possibility to filter products without refreshing the page with ajax. i update the url to make it look like :
http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4
where the int values are id's split by -.
so i have the options:
style
price
brand
color
what i want is get these values in a var for each filter option so that i end with :
var styleValues = 7,1,2
var priceValues = 4,5,7
if only price filter is selected the url will look like
http://mywebsite.com/products/filter?price=4-5-7
so i cant split on the tags for the filters.
I really like to know what would be the best way to turn the url to different vars.
What i already know :
how to get the filter part:
var filterPart =window.location.search;
Great article on css tricks covering just this:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
JavaScript can access the current URL in parts. For this URL:
http://css-tricks.com/example/index.html
window.location.protocol = "http:"
window.location.host = "css-tricks.com"
window.location.pathname = "example/index.html"
So to get the full URL path in JavaScript:
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
If you need to breath up the pathname, for example a URL like http://css-tricks.com/blah/blah/blah/index.html, you can split the string on "/" characters
var pathArray = window.location.pathname.split( '/' );
Then access the different parts by the parts of the array, like
var secondLevelLocation = pathArray[0];
To put that pathname back together, you can stitch together the array and put the "/"'s back in:
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "/";
newPathname += pathArray[i];
}
Or like this::
http://css-tricks.com/snippets/javascript/get-url-variables/
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
maybe this can help you :
var Request = {
QueryString : function (item) {
var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
return svalue?svalue[1]:svalue;
},
queryAllString : function() {
var urlLocation = location.href;
var startPosition = urlLocation.indexOf("?");
if (startPosition < 0) {
return '';
} else {
return urlLocation.slice(startPosition);
}
}
}
If you want to get price,you can do like this:
Request.QueryString("price")
My own take on this problem would be:
// this is simply to compensate for the lack of a current document.location to search:
var documentURL = 'http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4',
tempA = document.createElement('a');
tempA.href = documentURL
var searches = {
'get': function() {
var queries = {
// a cache of all named parameters found:
'found': []
},
// stripping off the leading '?':
queryString = tempA.search.substring(1),
// getting the key-value pairs:
keyValues = queryString.split('&'),
// to be used withi the forEach():
pair;
keyValues.forEach(function(el) {
// creating an array consisting of the keyName and keyValue:
pair = el.split('=');
// if we have both a name and a value we proceed:
if (pair.length === 2) {
if (!queries[pair[0]]) {
// if there is no present entry for the current key, we:
// push the key to the 'found' array, and
// create a record in the queries object for that key
// containing an array of the found values:
queries.found.push(pair[0]);
queries[pair[0]] = pair[1].split('-');
} else {
// otherwise (there is an existing key in the queries object),
// we push the values to the end of the existing array:
queries[pair[0]].push(pair[1])
}
}
});
return queries;
}
};
var cachedSearches = searches.get(),
allKeys = cachedSearches.found;
allKeys.forEach(function(el){
console.log(el, cachedSearches[el], cachedSearches[el].join(', '));
});
References:
Array.prototype.forEach().
Array.prototype.join().
String.prototype.split().
Try
var filtered = {};
var url = "http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4";
var filters = url.split("?")[1].split("&");
filters.map(function(val) {
filtered[val.split("=")[0]] = val.split("=")[1].split("-").join(",")
});
console.log(filtered);
var filtered = {};
var url = "http://mywebsite.com/products/filter?style=7-1-2&price=4-5-7&brand=48-12-5&color=8-4";
var filters = url.split("?")[1].split("&");
filters.map(function(val, i) {
filtered[val.split("=")[0]] = val.split("=")[1].split("-").join(",");
document.body.innerText += (Object.keys(filtered)[i].toString() +": "+ filtered[val.split("=")[0]]) + "\n"
});
Let's say I have a url such as:
http://www.example.com/hello.png?w=100&h=100&bg=white
What I'd like to do is update the values of the w and h querystring, but leave the bg querystring intact, for example:
http://www.example.com/hello.png?w=200&h=200&bg=white
So what's the fastest most efficient way to read the querystring values (and they could be any set of querystring values, not just w, h, and bg), update a few or none of the values, and return the full url with the new querystring?
So:
Get the values of each querystring key
Update any number of the keys
Rebuild the url with the new values
Keep all of the other values which weren't updated
It will not have a standard set of known keys, it could change per URL
Simple solution
You can use URLSearchParams.set() like below:
var currentUrl = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var url = new URL(currentUrl);
url.searchParams.set("w", "200"); // setting your param
var newUrl = url.href;
console.log(newUrl);
Online demo (jsfiddle)
Get query string values this way and use $.param to rebuild query string
UPDATE:
This is an example, also check fiddle:
function getQueryVariable(url, variable) {
var query = url.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
var w = getQueryVariable(url, 'w');
var h = getQueryVariable(url, 'h');
var bg = getQueryVariable(url, 'bg');
// http://www.example.com/hello.png?w=200&h=200&bg=white
var params = { 'w':200, 'h':200, 'bg':bg };
var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);
You can change the function to use current url:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
//update URL Parameter
function updateURL(key,val){
var url = window.location.href;
var reExp = new RegExp("[\?|\&]"+key + "=[0-9a-zA-Z\_\+\-\|\.\,\;]*");
if(reExp.test(url)) {
// update
var reExp = new RegExp("[\?&]" + key + "=([^&#]*)");
var delimiter = reExp.exec(url)[0].charAt(0);
url = url.replace(reExp, delimiter + key + "=" + val);
} else {
// add
var newParam = key + "=" + val;
if(!url.indexOf('?')){url += '?';}
if(url.indexOf('#') > -1){
var urlparts = url.split('#');
url = urlparts[0] + "&" + newParam + (urlparts[1] ? "#" +urlparts[1] : '');
} else {
url += "&" + newParam;
}
}
window.history.pushState(null, document.title, url);
}
I like Ali's answer the best. I cleaned up the code into a function and thought I would share it to make someone else's life easier. Hope this helps someone.
function addParam(currentUrl,key,val) {
var url = new URL(currentUrl);
url.searchParams.set(key, val);
return url.href;
}
Another way (independent of jQuery or other libraries): https://github.com/Mikhus/jsurl
var u = new Url;
// or
var u = new Url('/some/path?foo=baz');
alert(u);
u.query.foo = 'bar';
alert(u);
My URL is like this: http://localhost/dentistryindia/admin/hospital/add_procedure?hid=241&hpr_id=12
var reExp = /hpr_id=\\d+/;
var url = window.location.href;
url = url.toString();
var hrpid = $("#category :selected").val(); //new value to replace hpr_id
var reExp = new RegExp("[\\?&]" + 'hpr_id' + "=([^&#]*)"),
delimeter = reExp.exec(url)[0].charAt(0),
newUrl = url.replace(reExp, delimeter + 'hpr_id' + "=" + hrpid);
window.location.href = newUrl;
This is how it worked for me.
Another way you you can do this, using some simple reg ex code by Samuel Santos here like this:
/*
* queryParameters -> handles the query string parameters
* queryString -> the query string without the fist '?' character
* re -> the regular expression
* m -> holds the string matching the regular expression
*/
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
// Creates a map with the query string parameters
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// Update w and h
queryParameters['w'] = 200;
queryParameters['h'] = 200;
Now you can either create a new URL:
var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname;
// Build new Query String
var params = $.param(queryParameters);
if (params != '') {
url = url + '?' + params;
}
OR you could just use the params to cause browser to reload right away:
location.search = params;
OR do whatever you want with :)
You could do something like this:
// If key exists updates the value
if (location.href.indexOf('key=') > -1) {
location.href = location.href.replace('key=current_val', 'key=new_val');
// If not, append
} else {
location.href = location.href + '&key=new_val';
}
Regards
URI.js seems like the best approach to me
http://medialize.github.io/URI.js/
let uri = URI("http://test.com/foo.html").addQuery("a", "b");
// http://test.com/foo.html?a=b
uri.addQuery("c", 22);
// http://test.com/foo.html?a=b&c=22
uri.hash("h1");
// http://test.com/foo.html?a=b&c=22#h1
uri.hash("h2");
// http://test.com/foo.html?a=b&c=22#h2
Alright, If you are someone like me who only wants to update query string on URL without reloading the page. try following code
updateQueryString('id',post.id)
function updateQueryString(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
$('.desktopsortpriceHandler').on('change', function(){
let price_id = $(this).val()
$('.btn_product_locality_filter').attr("href", function (i, val) {
// if p is in between of url
val = val.replace(/p=.*?&/i, ""); ----> this will help to get the parameter using regex and replace it with ""
// if p at the end of url
val = val.replace(/&p=.*?$/i, ""); ----> this will help to get the parameter using regex and replace it with ""
return val + `&p=${encodeURIComponent(price_id.toString())}`; ---> then you can add it back as parameter with new value
});
})
i'm using this
function UpdateUrl(a,b,c,pagetitle) {
var url = window.location.href;
var usplit = url.split("?");
var uObj = { Title: pagetitle, Url: usplit[0] + "?w=a&h=b&bg=c};
history.pushState(uObj, uObj.Title, uObj.Url);
}
I've been looking for an efficient way to do this but haven't been able to find it, basically what I need is that given this url for example:
http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100
I'd like to be able to change the URL in the src parameter with another value using javascript or jquery, is this possible?
The following solution combines other answers and handles some special cases:
The parameter does not exist in the original url
The parameter is the only parameter
The parameter is first or last
The new parameter value is the same as the old
The url ends with a ? character
\b ensures another parameter ending with paramName won't be matched
Solution:
function replaceUrlParam(url, paramName, paramValue)
{
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
if (url.search(pattern)>=0) {
return url.replace(pattern,'$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/,'');
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}
Known limitations:
Does not clear a parameter by setting paramValue to null, instead it sets it to empty string. See https://stackoverflow.com/a/25214672 if you want to remove the parameter.
Nowdays that's possible with native JS
var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs
Wouldn't this be a better solution?
var text = 'http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100';
var newSrc = 'www.google.com';
var newText = text.replace(/(src=).*?(&)/,'$1' + newSrc + '$2');
EDIT:
added some clarity in code and kept 'src' in the resulting link
$1 represents first part within the () (i.e) src= and $2 represents the second part within the () (i.e) &, so this indicates you are going to change the value between src and &. More clear, it should be like this:
src='changed value'& // this is to be replaced with your original url
ADD-ON for replacing all the ocurrences:
If you have several parameters with the same name, you can append to the regex global flag, like this text.replace(/(src=).*?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.
Javascript now give a very useful functionnality to handle url parameters: URLSearchParams
var searchParams = new URLSearchParams(window.location.search);
searchParams.set('src','newSrc')
var newParams = searchParams.toString()
Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:
/search?searchquery=text and 'query' is provided.
In this case searchquery param value is changed.
Code:
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
In modern browsers (everything except IE9 and below), our lives are a little easier now with the new URL api
var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
url.searchParams.set("foo", "bar");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
url.searchParams.set("foo", "ooft");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
// Set new or modify existing parameter value.
queryParams.set("myParam", "myValue");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
history.pushState(null, null, "?"+queryParams.toString());
If you are having very narrow and specific use-case like replacing a particular parameter of given name that have alpha-numeric values with certain special characters capped upto certain length limit, you could try this approach:
urlValue.replace(/\bsrc=[0-9a-zA-Z_#.#+-]{1,50}\b/, 'src=' + newValue);
Example:
let urlValue = 'www.example.com?a=b&src=test-value&p=q';
const newValue = 'sucess';
console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_#.#+-]{1,50}\b/, 'src=' + newValue));
// output - www.example.com?a=b&src=sucess&p=q
I have get best solution to replace the URL parameter.
Following function will replace room value to 3 in the following URL.
http://example.com/property/?min=50000&max=60000&room=1&property_type=House
var newurl = replaceUrlParam('room','3');
history.pushState(null, null, newurl);
function replaceUrlParam(paramName, paramValue){
var url = window.location.href;
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
if (url.search(pattern)>=0) {
return url.replace(pattern,'$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/,'');
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}
Output
http://example.com/property/?min=50000&max=60000&room=3&property_type=House
Editing a Parameter
The set method of the URLSearchParams object sets the new value of the parameter.
After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
The final new url can then be retrieved with the toString() method of the URL object.
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
// new value of "id" is set to "101"
search_params.set('id', '101');
// change the search property of the main url
url.search = search_params.toString();
// the new url string
var new_url = url.toString();
// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);
Source - https://usefulangle.com/post/81/javascript-change-url-parameters
UpdatE: Make it into a nice function for you: http://jsfiddle.net/wesbos/KH25r/1/
function swapOutSource(url, newSource) {
params = url.split('&');
var src = params[0].split('=');
params.shift();
src[1] = newSource;
var newUrl = ( src.join('=') + params.join('&'));
return newUrl;
}
Then go at it!
var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");
console.log(newUrl);
If you look closely you'll see two surprising things about URLs: (1) they seem simple, but the details and corner cases are actually hard, (2) Amazingly JavaScript doesn't provide a full API for making working with them any easier. I think a full-fledged library is in order to avoid people re-inventing the wheel themselves or copying some random dude's clever, but likely buggy regex code snippet. Maybe try URI.js (http://medialize.github.io/URI.js/)
I use this method which:
replace the url in the history
return the value of the removed parameter
function getUrlParameterAndRemoveParameter(paramName) {
var url = window.location.origin + window.location.pathname;
var s = window.location.search.substring(1);
var pArray = (s == "" ? [] : s.split('&'));
var paramValue = null;
var pArrayNew = [];
for (var i = 0; i < pArray.length; i++) {
var pName = pArray[i].split('=');
if (pName[0] === paramName) {
paramValue = pName[1] === undefined ? true : decodeURIComponent(pName[1]);
}
else {
pArrayNew.push(pArray[i]);
}
}
url += (pArrayNew.length == 0 ? "" : "?" + pArrayNew.join('&'));
window.history.replaceState(window.history.state, document.title, url);
return paramValue;
}
In addition to #stenix, this worked perfectly to me
url = window.location.href;
paramName = 'myparam';
paramValue = $(this).val();
var pattern = new RegExp('('+paramName+'=).*?(&|$)')
var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
var n=url.indexOf(paramName);
alert(n)
if(n == -1){
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
window.location.href = newUrl;
Here no need to save the "url" variable, just replace in current url
How about something like this:
<script>
function changeQueryVariable(keyString, replaceString) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var replaced = false;
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == keyString) {
vars[i] = pair[0] + "="+ replaceString;
replaced = true;
}
}
if (!replaced) vars.push(keyString + "=" + replaceString);
return vars.join("&");
}
</script>
try this
var updateQueryStringParam = function (key, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
urlQueryString = document.location.search,
newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');
if( typeof value == 'undefined' || value == null || value == '' ) { // Remove param if value is empty
params = urlQueryString.replace(removeRegex, "$1");
params = params.replace( /[&;]$/, "" );
} else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it
params = urlQueryString.replace(updateRegex, "$1" + newParam);
} else { // Otherwise, add it to end of query string
params = urlQueryString + '&' + newParam;
}
}
// no parameter was set so we don't need the question mark
params = params == '?' ? '' : params;
window.history.replaceState({}, "", baseUrl + params);
};
A solution without Regex, a little bit easier on the eye, one I was looking for
This supports ports, hash parameters etc.
Uses browsers attribute element as a parser.
function setUrlParameters(url, parameters) {
var parser = document.createElement('a');
parser.href = url;
url = "";
if (parser.protocol) {
url += parser.protocol + "//";
}
if (parser.host) {
url += parser.host;
}
if (parser.pathname) {
url += parser.pathname;
}
var queryParts = {};
if (parser.search) {
var search = parser.search.substring(1);
var searchParts = search.split("&");
for (var i = 0; i < searchParts.length; i++) {
var searchPart = searchParts[i];
var whitespaceIndex = searchPart.indexOf("=");
if (whitespaceIndex !== -1) {
var key = searchPart.substring(0, whitespaceIndex);
var value = searchPart.substring(whitespaceIndex + 1);
queryParts[key] = value;
} else {
queryParts[searchPart] = false;
}
}
}
var parameterKeys = Object.keys(parameters);
for (var i = 0; i < parameterKeys.length; i++) {
var parameterKey = parameterKeys[i];
queryParts[parameterKey] = parameters[parameterKey];
}
var queryPartKeys = Object.keys(queryParts);
var query = "";
for (var i = 0; i < queryPartKeys.length; i++) {
if (query.length === 0) {
query += "?";
}
if (query.length > 1) {
query += "&";
}
var queryPartKey = queryPartKeys[i];
query += queryPartKey;
if (queryParts[queryPartKey]) {
query += "=";
query += queryParts[queryPartKey];
}
}
url += query;
if (parser.hash) {
url += parser.hash;
}
return url;
}
2020 answer since I was missing the functionality to automatically delete a parameter, so:
Based on my favorite answer https://stackoverflow.com/a/20420424/6284674 :
I combined it with the ability to:
automatically delete an URL param if the value if null or '' based on answer https://stackoverflow.com/a/25214672/6284674
optionally push the updated URL directly in the window.location bar
IE support since it's only using regex and no URLSearchParams
JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/
function replaceUrlParam(url, paramName, paramValue){
if(paramValue == null || paramValue == "")
return url
.replace(new RegExp('[?&]' + paramValue + '=[^&#]*(#.*)?$'), '$1')
.replace(new RegExp('([?&])' + paramValue + '=[^&]*&'), '$1');
url = url.replace(/\?$/,'');
var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
if(url.search(pattern)>=0){
return url.replace(pattern,'$1' + paramValue + '$2');
}
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
// Orginal URL (default jsfiddle console URL)
//https://fiddle.jshell.net/_display/?editor_console=true
console.log(replaceUrlParam(window.location.href,'a','2'));
//https://fiddle.jshell.net/_display/?editor_console=true&a=2
console.log(replaceUrlParam(window.location.href,'a',''));
//https://fiddle.jshell.net/_display/?editor_console=true
console.log(replaceUrlParam(window.location.href,'a',3));
//https://fiddle.jshell.net/_display/?editor_console=true&a=3
console.log(replaceUrlParam(window.location.href,'a', null));
//https://fiddle.jshell.net/_display/?editor_console=true&
//Optionally also update the replaced URL in the window location bar
//Note: This does not work in JSfiddle, but it does in a normal browser
function pushUrl(url){
window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));
}
pushUrl(replaceUrlParam(window.location.href,'a','2'));
//https://fiddle.jshell.net/_display/?editor_console=true&a=2
pushUrl(replaceUrlParam(window.location.href,'a',''));
//https://fiddle.jshell.net/_display/?editor_console=true
pushUrl(replaceUrlParam(window.location.href,'a',3));
//https://fiddle.jshell.net/_display/?editor_console=true&a=3
pushUrl(replaceUrlParam(window.location.href,'a', null));
//https://fiddle.jshell.net/_display/?editor_console=true&
Here is function which replaces url param with paramVal
function updateURLParameter(url, param, paramVal){
if(!url.includes('?')){
return url += '?' + param + '=' + paramVal;
}else if(!url.includes(param)){
return url += '&' + param + '=' + paramVal;
}else {
let paramStartIndex = url.search(param);
let paramEndIndex = url.indexOf('&', paramStartIndex);
if (paramEndIndex == -1){
paramEndIndex = url.length;
}
let brands = url.substring(paramStartIndex, paramEndIndex);
return url.replace(brands, param + '=' + paramVal);
}
}
A lengthier, but maybe more flexible, answer that relies on two functions. The first one produces a key/value dictionary with all the parameters, the other one doing the substitution itself. This should work on old browsers, and can also create the parameter when it doesn't exist.
var get_all_params=function(url)
{
var regexS = /(?<=&|\?)([^=]*=[^&#]*)/;
var regex = new RegExp( regexS,'g' );
var results = url.match(regex);
if(results==null)
{
return {};
}
else
{
returned={};
for(i=0;i<results.length;i++)
{
var tmp=results[i];
var regexS2="([^=]+)=([^=]+)";
var regex2 = new RegExp( regexS2 );
var results2 = regex2.exec(tmp );
returned[results2[1]]=results2[2];
}
return returned;
}
}
var replace_param=function(url, param, value)
{
var get_params=get_all_params(url);
var base_url=url.split("?");
get_params[param]=value;
var new_params=Array();
for(key in get_params)
{
new_params.push(key+"="+get_params[key]);
}
return base_url[0]+"?"+new_params.join("&");
}
Exemple of call :
var url ="https://geoserver.xxx.com/geoserver/project?service=WFS&version=1.0.0&request=GetFeature&typename=localities";
url=replace_param(url, "service","WMS");