Query String in JavaScript - javascript

By using document.referrer we will get all the reference of URL in JavaScript, such as the following:
http://localhost/testwordpress/wp-admin/admin.php?page=thesis-options&upgraded=true
From this output how can we extract the query string part only:
?page=thesis-options&upgraded=true
Is there any method in JavaScript?

To get the query string from document.referrer, you can use the split() method:
var qs = document.referrer.split('?')[1];
if (typeof qs !== 'undefined') {
// qs contains the query string.
// this would be "page=thesis-options&upgraded=true" in your case.
}
else {
// there was no query string in document.referrer.
}

If you are just looking to get the values from the query string I use the following function:
function getQuerystring(key)
{
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
Simply pass in the key you are looking for and get the value back.
IE: getQueryString('upgraded') would return true

There are some functions around to do that. See this for example.

Related

how to replace/ remove a substring if a string contains that substing

I am writing a function that detects if the current URL contains a certain substring. If it contains, then I would like to remove it.
For example,
localhost/4000?ab=2&item=google
localhost/4000?ab=2&item=google123
localhost/4000?ab=2&item=google1233&haha=helpful
My idea is below....but kinda stuck in the process
function changeUrl(item) {
var currentUrl = window.location.href;
if(currentUrl.includes('&item=') ){
.....
.....
return currentUrl
}else return;
}
I wouldn't try to manipulate it as a string. JavaSccript has a perfectly good tool to manipulate URLs, and you might as well use it:
str = 'http://localhost/4000?ab=2&item=google1233&haha=helpful';
url = new URL(str);
url.searchParams.delete('item'); // Idempotent call
result = url.toString();
In this case, it's better to use URLSearchParams.
MDN DOCS
The URLSearchParams interface defines utility methods to work with the query string of a URL.
var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);
// you can see params by this way
for (let p of params) {
console.log(p);
}
// if you want to check if some params are exist
console.log(params.has('foo')); // true
// if you want to delete some params
console.log(params.toString());
params.delete('foo');
console.log(params.toString());

If location.search == '?test=yes' any anything after does something else

I am trying to use the query string in my javascript in my website, is there like a wildcard tag in javascript so it could be like
* = wildcard
var x = location.search;
if (x=='?test=yes') {
window.location.replace('http://google.com')
}
else {
if (x=='?test=yes&*=123') {
window.location.replace('http://youtube.com')
}
}
Would this be possible?
Just use includes:
const x = "https://example.com?test=yes&*=123";
console.log(x.includes("?test=yes"));
You could alternatively use a regular expression:
const x = "https://example.com?test=yes&*=123";
console.log(/]?test=yes/.test(x));
There is a built in class to handle this now.
var params = new URL(location.href).searchParams;
This will return a URLSearchParams object that you can use to check the query string.
if(params.has('test')){
console.log(params.get('test'));
}
One way of achieving this would be with .includes(), wherein you can simply check that x contains the starting string ?test=yes:
const x = '?test=yes&*=123';
if (x.includes('?test=yes')) {
console.log('yes');
}

Getting URL parameters and filter out a specific parameter

I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);

Query String in Javascript

How can we collect a query string value in javascript.
my script is like follows
http://192.168.10.5/study/gs.js?id=200
here i want to collect the id value in my gs.js script file.
For this i am using
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
var string_value = getQuerystring('id');
alert(string_value);
But it is not getting..Please anybody can correct me.Please
This function gets the query string of the page hosting this script: it relies on window.location.href. It seems that http://192.168.10.5/study/gs.js?id=200 is the address of the script itself and not the page. In order to do this you will need to first obtain this address by looking at the script tags in your document and then slightly modify the previous function to take an additional parameter representing the url and not relying on window.location.href.
From my programming archive:
function querystring(key) {
var re = new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null) r[r.length] = m[1];
return r;
}
The function returns the found values as an array with zero or more strings.
Usage:
var values = querystring('id');
if (values.length > 0) {
// use values[0] to get the first (and usually only) value
// or loop through values[0] to values[values.length-1]
}
or:
var string_value = querystring('id').toString();

How to get "GET" request parameters in JavaScript? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
How to get "GET" variables from request in JavaScript?
Does jQuery or YUI! have this feature built-in?
Update June 2021:
Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).
Original:
All data is available under
window.location.search
you have to parse the string, eg.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
just call the function with GET variable name as parameter, eg.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
You could use jquery.url I did like this:
var xyz = jQuery.url.param("param_in_url");
Check the source code
Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser
try the below code, it will help you get the GET parameters from url .
for more details.
var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)
Just to put my two cents in, if you wanted an object containing all the requests
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
var QueryString = getRequests();
//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3
Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.
function Request(name){
return QueryString[name.toLowerCase()];
}
Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:
var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)
You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.
A map-reduce solution:
var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
Usage:
For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.
If you already use jquery there is a jquery plugin that handles this:
http://plugins.jquery.com/project/query-object
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
Works for me in
url: http://localhost:8080/#/?access_token=111
function get(name){
const parts = window.location.href.split('?');
if (parts.length > 1) {
name = encodeURIComponent(name);
const params = parts[1].split('&');
const found = params.filter(el => (el.split('=')[0] === name) && el);
if (found.length) return decodeURIComponent(found[0].split('=')[1]);
}
}

Categories