Getting data from url hash in javascript - javascript

I am trying to read the "source" parameter and the "group" parameter from the url hash below. I have no idea how to use regex and keep ending up with blank variables.
How do I read "source" and "group" parameters from the url hash below
console.log(urlObj.hash); // #source-items?source=1002&?group=Menu
var source = urlObj.hash.replace( /.*source=/, "");

If you remove the ? after & and you can use something like this:
function parseParams() {
var params = window.location.hash.split('?')[1].split('&').map(function(item) {
return item.split('=');
});
var namedparams = {};
for (i=-1; param = params[++i]; ) {
namedparams[param[0]] = param[1];
}
return namedparams;
}
This is how you use this function:
var params = parseParams();
params.group; // the group parameter
params.source; // the source parameter

Try
function getParameterByName(urlString, name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(urlString);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
And invoke this by getParameterByName(urlObj.hash, "source");
Update : This is slightly modified version of the answer to Get query string values in JavaScript

Related

Case-Sensitive Jquery getQuery URL Param

I'm hoping this is a quick answer for someone. I have built a form that is passing a few query params to the end of the URL and I'm using Jquery to get the param values based on the param names. My JQuery code seems to be case-sensitive which is causing some issues. For example, my param name is 'Blah' and my Jquery code is looking for 'blah', and it it won't work. Is there an easy way to update this code to be case-insensitive so that I don't have to manually account for all possible cases (e.g. blah, Blah, BLAH, blAh, blaH, etc.)?
Sample Jquery Code:
(function ($) {
$.getQuery = function (query) {
query = query.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var expr = "[\\?&]" + query + "=([^&#]*)";
var regex = new RegExp(expr);
var results = regex.exec(window.location.href);
if (results !== null) {
return results[1];
return decodeURIComponent(results[1].replace(/\+/g, " "));
} else {
return false;
}
};
})(jQuery);
var lang = $.getQuery('blah');
I also have similar code that I'm using in JavaScript that is case-sensitive too. Is there an easy way to change this code to be case-insensitive as well?
var dURL = document.URL;
function getParams() { //Get Name and (=) Values out of URL string after each &
var idx = dURL.indexOf('?');
var pnd = dURL.indexOf('#');
var fparams = new Array();
if (idx > -1) {
if (pnd > idx) {
var pairs = dURL.substring(idx + 1, (pnd - idx)).split('&');
} else {
var pairs = dURL.substring(idx + 1, document.URL.length).split('&');
}
for (var i = 0; i < pairs.length; i++) {
nameVal = pairs[i].split('=');
fparams[nameVal[0]] = nameVal[1];
}
}
return fparams;
}
var params = getParams();
if (params["blah"] != window.undefined) {
lang = unescape(params["blah"]);
} else {
blah= '';
}
Any information that can be provided would be greatly appreciated!
Using js toLower should work
(function ($) {
$.getQuery = function (query) {
query = query.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var expr = "[\\?&]" + query + "=([^&#]*)";
var regex = new RegExp(expr);
var results = regex.exec(window.location.href.toLower());
if (results !== null) {
return results[1];
return decodeURIComponent(results[1].replace(/\+/g, " "));
} else {
return false;
}
};
})(jQuery);

how to remove query string arrays from url in javascript

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.

Updating existing URL querystring values with jQuery

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);
}

How to replace url parameter with javascript/jquery?

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");

Get querystring from URL using jQuery [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 3 years ago.
I have the following URL:
http://www.mysite.co.uk/?location=mylocation1
I need to get the value of location from the URL into a variable and then use it in jQuery code:
var thequerystring = "getthequerystringhere"
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
How can I grab that value using JavaScript or jQuery?
From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
This is what you need :)
The following code will return a JavaScript Object containing the URL parameters:
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
For example, if you have the URL:
http://www.example.com/?me=myValue&name2=SomeOtherValue
This code will return:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
and you can do:
var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
To retrieve the entire querystring from the current URL, beginning with the ? character, you can use
location.search
https://developer.mozilla.org/en-US/docs/DOM/window.location
Example:
// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123"
In regards to retrieving specific querystring parameters, while although classes like URLSearchParams and URL exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:
/**
* Accepts either a URL or querystring and returns an object associating
* each querystring parameter to its value.
*
* Returns an empty object if no querystring parameters found.
*/
function getUrlParams(urlOrQueryString) {
if ((i = urlOrQueryString.indexOf('?')) >= 0) {
const queryString = urlOrQueryString.substring(i+1);
if (queryString) {
return _mapUrlParams(queryString);
}
}
return {};
}
/**
* Helper function for `getUrlParams()`
* Builds the querystring parameter to value object map.
*
* #param queryString {string} - The full querystring, without the leading '?'.
*/
function _mapUrlParams(queryString) {
return queryString
.split('&')
.map(function(keyValueString) { return keyValueString.split('=') })
.reduce(function(urlParams, [key, value]) {
if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
urlParams[key] = parseInt(value);
} else {
urlParams[key] = decodeURI(value);
}
return urlParams;
}, {});
}
You can use the above like so:
// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }
// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }
// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName')) {
console.log(urlParams.parameterName);
}
An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
Have a look at this Stack Overflow answer.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
You can use the method to animate:
I.e.:
var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
We do it this way...
String.prototype.getValueByKey = function (k) {
var p = new RegExp('\\b' + k + '\\b', 'gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};

Categories