Read path using javascript - javascript

Suppose I am loading a JavaScript file like this:
<script type="text/javascript" src="http://foo.com/script.js?id=120#foo"></script>
Is it possible to read GET or hash parameter passing through this?
I am currently doing this using PHP (with headers) like:
<script type="text/javascript" src="http://foo.com/script.php?id=120"></script>

Look here, and replace the window.loaction with your src string.
How to retrieve GET parameters from javascript?
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
var params = getSearchParameters();
to get the string:
var str = $('script').attr('src')
or without jQuery:
document.querySelectorAll('script')[0].src

Related

How to find the parameter key from window location path?

I have query string is as follows.
Window.location.href = http://192.168.1.25:9990/myprofile?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs
I am trying window.location.search I am getting ?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs
But expected output : IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs I need without ?
Try:
window.location.search.substring(1)
You can use searchParams.get() like this example :
var currentUrl = Window.location.href;
var url = new URL(currentUrl);
var c = url.searchParams.get("myprofile");
Check this link
var urlStr = "http://192.168.1.25:9990/myprofile?IkNBMTEyOTA4MjYyOSI.5sTmOAZU-ZNmqDpVIx4SnLjzsMs";
function getqueryString(url) {
var retObj = {};
if (!url) return retObj;
var str = url.split('?')[1];
if (!str) return retObj;
var query = str.split('&');
for (var i = 0; i < query.length; i++) {
var pair = query[i].split('=');
retObj[pair[0]] = pair[1];
}
return retObj;
}
var rsl = getqueryString(urlStr);
console.log(rsl)
You can use this function it takes URL as the parameter and returns Back all the query parameter in an object form

how to get parameters from url in javascript?

I am trying to get query parameters from the URL in javascript. I tried window.location.search and got the params but it happens only the first time I access the URL. Afterwards it is returning empty.
I read somewhere that it is due to Asynchronous GET request. So how to get parameters always from the URL in javascript?
This might can help for you.
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
function Myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id="); //will return the parameter after "?"
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
You can use the new javascript APIs, URL and URLSearchParams
var link = new URL('https://google.com.ec?q=blable%20bli&q=2312&dog=true')
var params = link.searchParams
var keys = [...new Set([...params.keys()])]
console.log('keys: ', keys)
for (var key of keys)
console.log(key, params.getAll(key))

Prase query string from url javascript

my url look like http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1
now i am looking for a function where i will pass url and query string name then that should return value.
so i did it this way but not working.
function getQueryVariable(url,variable) {
var query = url;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
calling like this way
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert(getQueryVariable(x,'sort'));
alert(getQueryVariable(x,'sortdir'));
alert(getQueryVariable(x,'page'));
where i made the mistake?
EDIT
working code
$.urlParam = function(url,name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert($.urlParam(x,'sort'));
alert($.urlParam(x,'sortdir'));
alert($.urlParam(x,'page'));
https://jsfiddle.net/z99L3985/1/
thanks
may be the following will help
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1';
var queryVars = getUrlVars(x);
alert(queryVars['sort']);
alert(queryVars['sortdir']);
alert(queryVars['page']);
I just get this from somewhere else as well..
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
console.log(vars);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] === variable){return pair[1];}
}
return(false);
}
so far its doing its job.
with url: "http://urlhere.com/general_journal?from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2"
if im going to get the 'page' variable result would be : `2`
console.log(getQueryVariable('page'));
my query variable is only getting the search.substring(1) part of the the url so basically it only gets from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2 part of the url then from that it splits it and then return the value of the string parameter you specified on the function call getQueryVariable('page') for example.
Maybe this helps
var getUrlVars = function(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == url){
vars =[];
}
return vars;
}
Then in your code
var params = getUrlVars("http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1");
console.log(params["sort"]) // FirstName

How to get an url contained in query string

I want a javascript variable to be what is behind the ?url= in the url..
for example: The current url is
http://mywebsite.com/test/index.html?url=http://www.google.com/
So the variable has to be http://www.google.com/ .
I tried this, but it doesn't work… why ?
var url = document.URL ;
var appname = url.match(?url=(.+))[1];
Thanks.
I think the following will work for you:
function querystring(key) {
var query = window.location.search.substring(1);
var keys = query.split("&");
for (i = 0; i < keys.length; i++) {
var values = keys[i].split("=");
if (values[0] == key) {
return values[1];
}
}
}
var appname = querystring("url");
alert(appname);
Try this:
var regex = /\?url\=(.+)/;
var appname = regex.exec(url)[1];
or even simpler:
var appname = /\?url\=(.+)/.exec(url)[1];
var url = location.search.match(/url=([^&]+)&*.*$/)[1]; // http://www.google.com/
location //location object
.search //the search part in location
.match //return string according to regex given
[1] //second result (result in parenthesis)
//--------Use in a function---------
function getQuery(txt){
var result = location.search.match(new RegExp(txt + "=([^&]+)&*.*$"));
return result === null ? undefined : result[1];
}
http://jsfiddle.net/DerekL/J4FfZ/

Google Minify + Pass Variable

I'm using Google Minify to compress js files successfully.
I need to be able to pass a variable (like a $_GET variable) with this.
<script type="text/javascript" src="includes/min/?g=site_searchresults_js"></script>
Is there a way to pass a variable with the above code?
The process of determining the query string parameters that were passed when the script was added into the document is described in this article. It comes down to this kind of code:
var scripts = document.getElementsByTagName('script');
var myScript = scripts[ scripts.length - 1 ];
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
var params = parseQuery( queryString );
function parseQuery ( query ) {
var Params = new Object ();
if ( ! query ) return Params; // return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) continue;
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}

Categories

Resources