how to get parameters from url in javascript? - 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))

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 initialize an element in an HTML page

I want to pass through the text data entered on the /index page (property address) and (email) to the /sign-up page.
problem:
The query string(s) are moving into the URL, however how do I populate the respective fields on the /sign-up page, with the text data provided in the URL?
www.juwai.kiwi
<script>
(function(f, e, t){
initForm(f, e, t);
}(document.forms[0],'full_name',document.getElementsByName('full_name').valueOf()));
</script>
<script>
function initForm(oForm, element_name, init_txt) {
frmElement = oForm.elements[element_name];
frmElement.value = init_txt;
};
var queryStrng = [
{
full_name: "dave",
email: "email#to.do",
property_address: "prop address to do"
}
];
//queryStrng[0].full_name = document.getElementsByName("full_name").valueOf();
//var oFormObject = document.forms[0];
</script>
Try this function:
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
And this is how you can use this function assuming the URL is,
http://www.juwai.kiwi/sign-up.html?property_address=abcd&email=myemail%40gmail.com
var property_address = GetURLParameter('property_address');
var email = GetURLParameter('email');`

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/

scrape id from url using javascript

I have the following URL:
http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.
Where bi is a identifier for the specific book.
How can I extract the book id from the link?
Thanks!
You can to use this regex:
var address = "http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&...";
var bi = /[\?&]bi=(\d+)/.exec(address)[1]
alert(bi)
function getBookId()
{
var query = document.location.split("?")[1];
var values = query.split("&");
for(var i = 0; i < values.length; i++)
{
a = values[i].split("=");
if(a[0] === "bi")
return a[1];
}
//some error occurred
return null;
}
You can extract the book id (assumed to be only numbers) via a regular expression (and grouping).
var s = "http://www.abebooks.com/servlet/BookDetailsPL?\
bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.\
%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE\
%2527S%2BGARDEN."
var re = /bi=([0-9]+)&/; // or equally: /bi=(\d+)&/
var match = re.exec(s);
match[1]; // => contains 1325819827
address.split("bi=")[1].split("&")[0]
Try this
var bookId
var matcher = location.search.match(/(?:[?&]bi=([^&]+))/); // Assuming window.location
if (null !== matcher) {
bookId = matcher[1];
}
I once had the same problem.
I created a little function to help me out. Don't know where it is but I managed to recreate it:
function get(item,url) {
if (url == undefined)
url = window.location.href;
var itemlen = item.length
var items = url.split('?')[1].split('&');
for (var i = 0, len = items.length;i<len;i++) {
if (items[i].substr(0,itemlen) == item)
return items[i].split('=')[1];
}
return null;
}
So you would use it like:
get('bi');
If the url you gave was your current url, if not you could do:
get('bi','http://www.abebooks.com/servlet/BookDetailsPL?bi=1325819827&searchurl=an%3DLofting%252C%2BHugh.%26ds%3D30%26sortby%3D13%26tn%3DDOCTOR%2BDOLITTLE%2527S%2BGARDEN.')
Hope I didn't leave in any bugs :)

Categories

Resources