print value of URL Parameters hash js - javascript

I am trying to get the parameters from a URL using js i have a url :
http://www.example.com?i=aGVsbG8gd29ybGQ=
i want to decode base64 ?i value and print decode value here using javascript
<input id="i" type="hidden" value="decode value" />

Try this :
var parameterValue = atob(window.location.search.match(/(\?|&)i\=([^&]*)/)[2])
console.log(parameterValue);//"hello world"
document.getElementById('i').value=parameterValue;
This might help too : https://stackoverflow.com/a/26995016/957026

you could use the window.location API https://developer.mozilla.org/en-US/docs/Web/API/Location
console.log(window.location.search);
You will get as a response ?i=some-value

Yes you can get the value from url and and decode it.
Use below code
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
let x = atob(getUrlVars().i);
console.log(x); // hello world
document.getElementById('i').value = x;

To parse URL strings, modern browsers provide a class called URLSearchParams and this is the easiest way to extract URL values.
You can create an instance of that class by passing it the search property of window.location (after removing the initial "?"), and then it will do all the work for you:
// eg. https://example.com/?name=Jonathan&age=18&i=aGVsbG8gd29ybGQ=
const params = new URLSearchParams(window.location.search.substring(1)); // remove "?"
const name = params.get("name"); // is the string "Jonathan"
const age = parseFloat(params.get("age")); // is the number 18
const i = whateverDecodingFunctionYouUse(params.get("i")); // decoded aGVsbG8gd29ybGQ
See: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/

Related

ASP MVC JavaScript ActionLink multiple replace?

I want to build a Url.Action link and pass parameters and I found an example here on stackoverflow that shows how to replace the value:
var url = "#Url.Action("Export", "UserCalendar",new { from =
"_date", to="_to", groupId="_groupId" })".replace("_date",
_pdfExportStartDate);
How do I also replace _to and _groupId ? I tried
url = url.replace("_to",_pdfExportEndDate)
after the first replace call and although it makes the correct URL string the value (_to) is never passed to the controller.
You can simply add the querystring params to the base url (the one without any route values) as needed.
var _pdfExportStartDate = "11/11/2013";
var _toDate = "11/11/2013";
var baseUrl = "#Url.Action("Export", "UserCalendar")";
url = baseUrl +"?from = "+_pdfExportStartDate +"&to= "+ _toDate;

Search URL parameters with Angular JS

Say I have a URL like this:
www.mysite.com?account=23&token=asdu756sdg65sdf
Now, I need to access those URL parameters individually using Angular JS.
I've tried using location.search inside my controller:
console.log(location.search);
Which nicely returns the full query string:
?account=23&token=asdu756sdg65sdf
But it seems to return a string, not an object. Is there an easy way to access the individual ids and values in the string?
I've also tried:
console.log($location.search());
Which seems to return an empty object.
Try with
var account = ($location.search()).account;
but the url should be like /#!/?account=1
have your tried using it as a function instead?
$location.search();
pure js way:
var getParamFromURL = function(_url) {
var url = _url;
var _paraString = url.indexOf("&") > -1 ? url.substring(url.indexOf("?") + 1, url.length).split("&") : url.substring(url.indexOf("?") + 1, url.length).split('');
var _paraObj = {};
for (i = 0; p = _paraString[i]; i++) {
_paraObj[p.substring(0, p.indexOf("=")).toLowerCase()] = p.substring(p.indexOf("=") + 1, p.length);
}
return _paraObj;
}
via angular js:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
Great. #Cooper is right.

How can I pass values from one html page to another html page using javascript

In first page im getting value in textbox i need to pass it to another page which is divided into 2 frames.
I need to display that value in first frame's html page.
Please provide me a simple example.
I tried with
window.document.getElementById("inputbox1").value
but im unable to get the value.
Please provide me a simple example.
I would go with localStorage, as #MicrosoftGoogle propose, but is not well supported yet, you can use pure javascript to achieve this. You will have something like this on your form page:
<form action="param-received.html" method="GET">
<input type="text" id="foo" name="foo">
<input type="submit" value="Send" name="submit" id="submit">
</form>
Once you click on Send button,you will be redirect to /param-received.html?foo=hola&submit=Send.
location.search attribute contains the chain of parameters.
? concatenates the URL and the string of parameters.
& separates multiple parameters.
= assigns a value to the variable.
Here is the complete code to process data sent on param-received.html:
<script language="JavaScript">
function processForm()
{
var parameters = location.search.substring(1).split("&");
var temp = parameters[0].split("=");
l = unescape(temp[1]);
alert(l); //Dialog with the text you put on the textbox
}
processForm();
</script>
Write the value in a cookie and read the cookie from the other page.
For writing and reading cookies check here
You could use the GET part of the request or cookies
if url parameters are an option you could use this
function getParameter(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
getParameter("page");
ref
http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html
another might be cookies
was beaten to the cookie part :p
edit indeed not a good cookie reference
this one is better http://www.w3schools.com/js/js_cookies.asp
function getValue(varname)
{
var url = window.location.href;
var qparts = url.split("?");
if (qparts.length == 1)
{
return "";
}
else{
var query = qparts[1];
var vars = query.split("&");
var value = "";
for (i=0;i<vars.length;i++)
{
var parts = vars[i].split("=");
if (parts[0] == varname)
{
value = parts[1];
break;
}
}
value = unescape(value);
// Convert "+"s to " "s
value.replace(/\+/g," ");
return value;
}
}
var VariableGot = getValue(YourPassingVariableName);
Just copy the function into your html file and pass your variable name to the function which is send through GET Method.Now You will get the value of the variable from url.

How to obtain the query string from the current URL with JavaScript?

I have URL like this:
http://localhost/PMApp/temp.htm?ProjectID=462
What I need to do is to get the details after the ? sign (query string) - that is ProjectID=462. How can I get that using JavaScript?
What I've done so far is this:
var url = window.location.toString();
url.match(?);
I don't know what to do next.
Have a look at the MDN article about window.location.
The QueryString is available in window.location.search.
If you want a more convenient interface to work with, you can use the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.
let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);
searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true
The URLSearchParams interface is now widely adopted in browsers (95%+ according to Can I Use), but if you do need to support legacy browsers as well, you can use a polyfill.
Use window.location.search to get everything after ? including ?
Example:
var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})
If you happened to use Typescript and have dom in your the lib of tsconfig.json, you can do:
const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');
// To append, you can also leverage api to avoid the `?` check
params.append('newKey', 'newValue');
You can use this for direct find value via params name.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
This will add a global function to access to the queryString variables as a map.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
window.location.query = function (source) {
var map = {};
source = source || this.search;
if ("" != source) {
var groups = source, i;
if (groups.indexOf("?") == 0) {
groups = groups.substr(1);
}
groups = groups.split("&");
for (i in groups) {
source = groups[i].split("=",
// For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
(groups[i].slice(-1) !== "=") + 1
);
// Key
i = decodeURIComponent(source[0]);
// Value
source = source[1];
source = typeof source === "undefined"
? source
: decodeURIComponent(source);
// Save Duplicate Key
if (i in map) {
if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
map[i] = [map[i]];
}
map[i].push(source);
}
// Save New Key
else {
map[i] = source;
}
}
}
return map;
}
window.location.query.makeString = function (source, addQuestionMark) {
var str = "", i, ii, key;
if (typeof source == "boolean") {
addQuestionMark = source;
source = undefined;
}
if (source == undefined) {
str = window.location.search;
}
else {
for (i in source) {
key = "&" + encodeURIComponent(i);
if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
str += key + addUndefindedValue(source[i]);
}
else {
for (ii = 0; ii < source[i].length; ii++) {
str += key + addUndefindedValue(source[i][ii]);
}
}
}
}
return (addQuestionMark === false ? "" : "?") + str.substr(1);
}
function addUndefindedValue(source) {
return typeof source === "undefined"
? ""
: "=" + encodeURIComponent(source);
}
}
Enjoy.
You can simply use URLSearchParams().
Lets see we have a page with url:
https://example.com/?product=1&category=game
On that page, you can get the query string using window.location.search and then extract them with URLSearchParams() class.
const params = new URLSearchParams(window.location.search)
console.log(params.get('product')
// 1
console.log(params.get('category')
// game
Another example using a dynamic url (not from window.location), you can extract the url using URL object.
const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest')
console.log(url.search)
// ?v=6xJ27BtlM0c&ab_channel=FliteTest
This is a simple working snippet:
const urlInput = document.querySelector('input[type=url]')
const keyInput = document.querySelector('input[name=key]')
const button = document.querySelector('button')
const outputDiv = document.querySelector('#output')
button.addEventListener('click', () => {
const url = new URL(urlInput.value)
const params = new URLSearchParams(url.search)
output.innerHTML = params.get(keyInput.value)
})
div {
margin-bottom: 1rem;
}
<div>
<label>URL</label> <br>
<input type="url" value="https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest">
</div>
<div>
<label>Params key</label> <br>
<input type="text" name="key" value="v">
</div>
<div>
<button>Get Value</button>
</div>
<div id="output"></div>
You can use this function, for split string from ?id=
function myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id=");
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");
here is the fiddle
window.location.href.slice(window.location.href.indexOf('?') + 1);
You can use the search property of the window.location object to obtain the query part of the URL. Note that it includes the question mark (?) at the beginning, just in case that affects how you intend to parse it.
You should take a look at the URL API that has helper methods to achieve this in it as the URLSearchParams: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
This is not currently supported by all modern browsers, so don't forget to polyfill it (Polyfill available using https://qa.polyfill.io/).
var queryObj = {};
if(url.split("?").length>0){
var queryString = url.split("?")[1];
}
now you have the query part in queryString
First replace will remove all the white spaces, second will replace all the '&' part with "," and finally the third replace will put ":" in place of '=' signs.
queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
So let say you had a query like abc=123&efg=456. Now before parsing, your query is being converted into something like {"abc":"123","efg":"456"}. Now when you will parse this, it will give you your query in json object.
8 years later, for a one-liner
const search = Object.fromEntries(new URLSearchParams(location.search));
Down-side, it does NOT work with IE11
To explain
The URLSearchParams interface defines utility methods to work with the query string of a URL. (From , https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
The Object.fromEntries() method transforms a list of key-value pairs into an object. (From, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries)
// For https://caniuse.com/?search=fromEntries
> Object.fromEntries(new URLSearchParams(location.search))
> {search: "fromEntries"}
Convert that into array then split with '?'
var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';
url.split('?')[1]; //ProjectID=462
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
Try this one
/**
* Get the value of a querystring
* #param {String} field The field to get the value of
* #param {String} url The URL to get the value from (optional)
* #return {String} The field value
*/
var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};
Let’s say your URL is http://example.com&this=chicken&that=sandwich. You want to get the value of this, that, and another.
var thisOne = getQueryString('this'); // returns 'chicken'
var thatOne = getQueryString('that'); // returns 'sandwich'
var anotherOne = getQueryString('another'); // returns null
If you want to use a URL other than the one in the window, you can pass one in as a second argument.
var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something'
Reference
I think it is way more safer to rely on the browser than any ingenious regex:
const parseUrl = function(url) {
const a = document.createElement('a')
a.href = url
return {
protocol: a.protocol ? a.protocol : null,
hostname: a.hostname ? a.hostname : null,
port: a.port ? a.port : null,
path: a.pathname ? a.pathname : null,
query: a.search ? a.search : null,
hash: a.hash ? a.hash : null,
host: a.host ? a.host : null
}
}
console.log( parseUrl(window.location.href) ) //stacksnippet
//to obtain a query
console.log( parseUrl( 'https://example.com?qwery=this').query )
This will return query parameters as an associative array
var queryParams =[];
var query= document.location.search.replace("?",'').split("&");
for(var i =0; i< query.length; i++)
{
if(query[i]){
var temp = query[i].split("=");
queryParams[temp[0]] = temp[1]
}
}
For React Native, React, and For Node project, below one is working
yarn add query-string
import queryString from 'query-string';
const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");
console.log(parsed.offset) will display 10

Extracting parameters from JavaScript include tag using a Regex

I am currently trying to parse parameters from a path to a JavaScript file (inside a script tag). At the moment I know which parameters I expect to be there but instead of looking for the expected params I would rather like to just extract all params given.
Example of the script tag which includes a JavaScript file:
<script type="text/javascript" src="https://url/widget.js?param1=A&param2=bb></script>
At the moment I'm just doing this (seperately for each parameter):
jQuery('script').each(function() {
var script = this;
if (!script.src) {
return;
}
var matchKey = script.match(/https\:\/\/url\/widget\.js\?param1=([A-Z]+)/);
if (matchKey) {
oSettings.param1 = matchKey[1];
}
}
So what I need is a regex that extracts both the name of the parameter and the value from the included sript.
Thanks for the assistance!
This tested function works:
function parse_query_vars(text)
{ // Extract name=value pairs from URL query string.
// Empty object to store name, value pairs.
var qvars = {},
// Capture non-empty query string in $1.
re_q = /\?([^#]+)/, // From '?' up to '#' or EOS.
// Capture variable name in $1 and value in $2.
re_nv = /([^=]+)=([^&]*)(?:&(amp;)?|$)/gi,
// Match array for query string and va=val pairs.
m = text.match(re_q),
// Query string plucked from URL
q = '';
// If there is a query string, copy to q var.
if (m) q = m[1];
while (m = re_nv.exec(q)) {
qvars[m[1]] = m[2];
}
return qvars; // Return results in object
}
It first extracts any query string from the URL, then iteratively parses out name=value pairs and returns the results in an object. It handles name value pairs separated by either & or & and works if the URL has a #fragment following the query.
Use something like this, or this, or this.
They're not all regex solutions, but then you don't necessarily need a regex. That was a detail that could probably have been left out of the question.
Hope that helps.
(This isn't actually tested)
var scripts = document.getElementsByTagName("script"), i = scripts.length;
var reMatch = /https\:\/\/url\/widget\.js/, path;
// find the correct script
do {
path = scripts[i--].src;
}
while (!reMatch.test(path));
var map = {}, pairs = path.substring(path.indexOf("?") + 1).split("&"), atoms;
i = pairs.length;
// extract the name-value pairs
while (i--) {
atoms = pairs[i].split("=");
map[decodeURIComponent(atoms[0])] = decodeURIComponent(atoms[1]);
}

Categories

Resources