How do i retrieve this information using javascript? - javascript

I want to retrieve the information between “tmad=” and “&tmpageid” using javascript.
example: www.url.com/tmad1234&tmpageid88

Assuming you mean www.url.com/tmad=1234&tmpageid88 the following should do the trick
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 (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
getQueryVariable("tmad");

Related

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 can I get query string parameter in Javascript or jQuery?

I have a link like this:
http://localhost:8162/UI/Link2.aspx?txt_temp=123abc
I want to get the value 123abc . I have followed this How can I get query string values in JavaScript? and
jquery get querystring from URL
$(document).ready(function () {
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;
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
onload = function () {
alert(getParameterByName('txt_temp'));
alert(getUrlVars()["txt_temp"]);
}
});
But it does not work.
Suppose you have URL with many params eg:-
"http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
Then in js you can do like:
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
OR
var url = window.location.href
then split main url like:
hashes = url.split("?")[1]
//hashes holds this output "txt_temp=123abc&a=1&b=2"
Then again you can split by & to get individual param
EDIT
Check this example:
function getUrlVars() {
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2";
var vars = {};
var hashes = url.split("?")[1];
var hash = hashes.split('&');
for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
vars[params[0]] = params[1];
}
return vars;
}
Output
getUrlVars()
Object {txt_temp: "123abc", a: "1", b: "2"}
It doesn't work because you're running the functions inside of onload, which doesn't fire inside of document.ready, because by the time the code inside of document.ready executes, onload has already fired. Just get your code out of the onload event:
http://jsfiddle.net/whp9hnsk/1/
$(document).ready(function() {
// Remove this, this is only for testing.
history.pushState(null, null, '/UI/Link2.aspx?txt_temp=123abc');
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;
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// You may also place this inside of a function,
// and execute it when you desire, but `onload` is not going
// to fire by itself, when inside of document.ready
alert(getParameterByName('txt_temp'));
alert(getUrlVars()["txt_temp"]);
});
This should get you started:
function parseQueryStr( str, obj ) {
// Return object
obj = obj || {};
// Looping through our key/values
var keyvalues = str.split('&');
for( var i=0; i<keyvalues.length; i++ ) {
// Break apart our key/value
var sides = keyvalues[i].split( '=' );
// Valid propery name
if( sides[0] != '' ) {
// Decoding our components
sides[0] = decodeURIComponent( sides[0] );
sides[1] = decodeURIComponent( sides.splice( 1, sides.length-1 ).join( '=' ) );
// If we have an array to deal with
if( sides[0].substring( sides[0].length - 2 ) == '[]' ) {
var arrayName = sides[0].substring( 0, sides[0].length - 2 );
obj[ arrayName ] = obj[ arrayName ] || [];
obj[ arrayName ].push( sides[1] );
}
// Single property (will overwrite)
else {
obj[ sides[0] ] = sides[1];
}
}
}
// Returning the query object
return obj;
}
var href = window.location.href.split('#');
var query = href[0].split('?');
query.splice(0,1);
var get = parseQueryStr(query.join('?'));
alert( get.txt_temp );
You can use:
var param = new URLSearchParams(urlString).get('theParamName');
Or if searching the current page:
var param = new URLSearchParams(location.search).get('theParamName');
you have to slice the everything before and after "=" so first answer is a bit incomplete. Here is the answer which works for querystrings includes "=" in it too :) Like:
https://localhost:5071/login?returnUrl=/writer/user?id=315&name=john
Thanks to user abhi
var getUrlVars = function () {
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]); //to get name before =
vars[hash[0]] = hashes[i].slice(hashes[i].indexOf('=') + 1); //to take everything after first =
}
return vars;
}
and then get it with
var url = window.getUrlVars()["returnUrl"];
so it will extract "/writer/user?id=315" with "=" too :)
I wrote this one liner with ES6 syntax which follows the method of the accepted answer.
function getParam(key){
return window.location.href.split('?')[1].split('&').filter(x=>x.split('=')[0]==key)[0].split('=')[1];
}
Use:
Lets say the current URL is: https://stackoverflow.com?question=30271461
getParams('question') //30271461

How can I grab variable from URL using JavaScript and display it on screen?

I am using the following script:
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];}
}
var id_is = getQueryVariable("id");
document.write(id_is);
return(false);
}
This script should grab the variable value and display it on screen. It only works if I use getQueryVariable("id"); in the console but using the document.write method it doesn't work. What am I doing wrong?
You should call document.write when the page is loaded .
<script type="text/javascript">
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];
}
}
}
var id_is = getQueryVariable("id");
window.onload = function(){
document.write(id_is);
}
</script>
You can create a function that gets the query parameter from a URL, such as this:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
If the query is hello and it equals world, i.e. http://www.website.com/index.html?hello=world.
Then you can use getURLParameter('hello') to return it.
var url =window.location.search;
function getQueryParam(name,url) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
}
var result=getQueryParam(id,url);
document.write(result);

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/

Categories

Resources