Related
This Works:
setTheme('#222','#000','wheat','red','wheat','none','none');
This does not work:=
var theme01 = "'#222','#000','wheat','red','wheat','none','none'"; <br>
setTheme(theme01);
console.log(theme01) = '#222','#000','wheat','red','wheat','none','none'
So the conversion to string messes it up somehow?
I will be toggling through various themes before capturing the canvas? I had it all working with CSS, but canvas does not capture css changes or css injection. So I now have it all ready to go using Vanilla Javascript, but need help after hours of testing searching just to pass a variable to my function. Grrr. Help!
I have only been at this for a couple of weeks, so it's a learning curve after working only in Wordpress.
function setTheme(topp,bott,txt,hlin,vlin,fOrb,sOrb) {
var xx = document.querySelectorAll(".hlin");
for (var i = 0; i < xx.length; i++) {
xx[i].style.stroke = hlin;
}
var xx = document.querySelectorAll(".vlin");
for (var i = 0; i < xx.length; i++) {
xx[i].style.stroke = vlin;
}
var xx = document.querySelectorAll(".txt");
for (var i = 0; i < xx.length; i++) {
xx[i].style.fill = txt;
}
document.getElementById("svg_20").style.fill = topp;
document.getElementById("svg_1").style.fill = bott;
document.getElementById("svg_2").style.fill = bott;
document.getElementById("svg_3").style.stroke = txt;
document.getElementById("svg_5").style.stroke = txt;
document.getElementById("svg_21").style.fill = fOrb;
document.getElementById("svg_21").style.stroke = sOrb;
};
Yep, you can’t exchange a list of parameters for a comma-separated string. You should use a data structure to store them, like an array or object. Here’s an example of how it would work with an object.
var theme01 = { topp: '#222', bott: '#000', txt: 'wheat' };
function setTheme ( options ) {
document.getElementById("svg_20").style.fill = options.topp;
document.getElementById("svg_1").style.fill = options.bott;
document.getElementById("svg_3").style.fill = options.txt;
}
setTheme( theme01 )
The string will be one parameter for your function. You can use Function.apply )1 with a splitted string as second parameter, or even simpler, use the spread operator 2). Demo:
1) Function.apply
2) spread operator
( () => {
const log = str => document.querySelector("#result").textContent += `${str} \n`;
const parameterString = "#222,#000,wheat";
// no dice
log("someFn(parameterString) => no dice");
someFn(parameterString);
// use apply
log("\nsomeFn.apply(null, parameterString.split(\",\")) => ah yes, that works");
someFn.apply(null, parameterString.split(","));
// or use spread operator
log("\nsomeFn(...parameterString.split(\",\")) => ah yes, that works too");
someFn(...parameterString.split(","));
function someFn(p1, p2, p3) {
log(p1);
log(p2);
log(p3);
}
})();
<pre id="result"></pre>
You can pass it as an array using spread syntax, you cannot however pass a string of items and have them be multiple parameters.
function setTheme(topp, bott, txt, hlin, vlin, fOrb, sOrb) {
console.log(topp)
console.log(bott)
console.log(txt)
console.log(hlin)
console.log(vlin)
console.log(fOrb)
console.log(sOrb)
}
let items = ['#222', '#000', 'wheat', 'red', 'wheat', 'none', 'none']
setTheme(...items)
I have a long URL that contains some data that I need to pull. I am able to get the end of the URL by doing this:
var data = window.location.hash;
When I do alert(data); I receive a long string like this:
#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600
note in the example the access token is not valid, just random numbers I input for example purpose
Now that I have that long string stored in a variable, how can I parse out just the access token value, so everything in between the first '=' and '&. So this is what I need out of the string:
0u2389ruq892hqjru3h289r3u892ru3892r32235423
I was reading up on php explode, and others java script specific stuff like strip but couldn't get them to function as needed. Thanks guys.
DEMO (look in your debug console)
You will want to split the string by the token '&' first to get your key/value pairs:
var kvpairs = document.location.hash.substring(1).split('&');
Then, you will want to split each kvpair into a key and a value:
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != 'access_token')
continue;
console.log(v); //Here's your access token.
}
Here is a version wrapped into a function that you can use easily:
function getParam(hash, key) {
var kvpairs = hash.substring(1).split('&');
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != key)
continue;
return v;
}
return null;
}
Usage:
getParam(document.location.hash, 'access_token');
data.split("&")[0].split("=")[1]
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
var requiredValue = str.split('&')[0].split('=')[1];
I'd use regex in case value=key pair changes position
var data = "#token_type=Bearer&access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&expires_in=3600";
RegExp("access_token=([A-Za-z0-9]*)&").exec(data)[1];
output
"0u2389ruq892hqjru3h289r3u892ru3892r32235423"
Looks like I'm a bit late on this. Here's my attempt at a version that parses URL parameters into a map and gets any param by name.
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
function urlToMap(url){
var startIndex = Math.max(url.lastIndexOf("#"), url.lastIndexOf("?"));
url = url.substr(startIndex+1);
var result = {};
url.split("&").forEach(function(pair){
var x = pair.split("=");
result[x[0]]=x[1];
});
return result;
}
function getParam(url, name){
return urlToMap(url)[name];
}
console.log(getParam(str, "access_token"));
To answer to your question directly (what's between this and that), you would need to use indexOf and substring functions.
Here's a little piece of code for you.
function whatsBetween (_strToSearch, _leftText, _rightText) {
var leftPos = _strToSearch.indexOf(_leftText) + _leftText.length;
var rightPos = _strToSearch.indexOf(_rightText, leftPos);
if (leftPos >= 0 && leftPos < rightPos)
return _strToSearch.substring(leftPos, rightPos);
return "";
}
Usage:
alert(whatsBetween, data,"=","#");
That said, I'd rather go with a function like crush's...
try this
var data = window.location.hash;
var d1 = Array();
d1 = data.split("&")
var myFilteredData = Array();
for( var i=0;i<d1.length;i++ )
{
var d2 = d1[i].split("=");
myFilteredData.push(d2[1]); //Taking String after '='
}
I hope it helps you.
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
If my url is http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112 using purely javascript how would I extract &client= so it would extract 123456789101112 and set it as var clientid = 123456789101112;
var clientid = (window.location.search.match(/[?&;]name=(\d+)/) || [])[1];
If it can contain more than numbers, use something like...
var clientid = (window.location.search.match(/[?&;]name=([^&;]+)/) || [])[1];
If the param could not be found, it will return undefined.
If you need to do this more often, you'd be better off with a generic solution.
try this:
var url = "http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112"
var name = url.substring(url.indexOf('&name='), url.length)
If you don't want to user regular expression like the other answer
For a more generic/reusable solution, you can use something like:
getParameter = function(paramName, url) {
if (! paramName) {
return null;
}
if (! url) {
url = window.location.href;
}
if (url.indexOf('?') == -1) {
return null;
}
url = url.substring(url.indexOf('?') + 1);
var params = url.split('&');
for (var index = 0; index < params.length; index++) {
var nameValue = params[index].split('=');
if (nameValue.length == 2 && nameValue[0] == paramName) {
return nameValue[1];
}
}
return null;
};
...then just call getParameter('client');.
Example here: http://jsfiddle.net/L7hbT/3/
Not as succinct as #alex, but you could do this
var a = 'http://link-ads.blogspot.com/?url=http://could-be-any-url.com&name=123456789101112';
var b = a.indexOf('name=');
var clientId = a.substring(b + 5);
alert(clientId);
Example: http://jsfiddle.net/jasongennaro/ubJe3/
How to extract the query string from the URL in javascript?
Thank you!
You can easily build a dictionary style collection...
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
And use it like this...
var qs = getQueryStrings();
var myParam = qs["myParam"];
If you're referring to the URL in the address bar, then
window.location.search
will give you just the query string part. Note that this includes the question mark at the beginning.
If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:
url.substring(url.indexOf("?"))
That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.
Here's the method I use...
function Querystring() {
var q = window.location.search.substr(1), qs = {};
if (q.length) {
var keys = q.split("&"), k, kv, key, val, v;
for (k = keys.length; k--; ) {
kv = keys[k].split("=");
key = kv[0];
val = decodeURIComponent(kv[1]);
if (qs[key] === undefined) {
qs[key] = val;
} else {
v = qs[key];
if (v.constructor != Array) {
qs[key] = [];
qs[key].push(v);
}
qs[key].push(val);
}
}
}
return qs;
}
It returns an object of strings and arrays and seems to work quite well.
(Strings for single keys, arrays for the same key with multiple values.)
You need to simple use following function.
function GetQueryStringByParameter(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
--- How to Use ---
var QueryString= GetQueryStringByParameter('QueryString');
Very Straightforward!
function parseQueryString(){
var assoc = {};
var keyValues = location.search.slice(1).split('&');
var decode = function(s){
return decodeURIComponent(s.replace(/\+/g, ' '));
};
for (var i = 0; i < keyValues.length; ++i) {
var key = keyValues[i].split('=');
if (1 < key.length) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
There is a new API called URLSearchParams in browsers which allow you to extract and change the values of the query string.
Currently, it seems to be supported in Firefox 44+, Chrome 49+ and Opera 36+.
Initialize/Input
To get started, create a new URLSearchParams object. For current implementations, you need to remove the "?" at the beginning of the query string, using slice(1) on the querystring, as Jake Archibald suggests:
var params = new URLSearchParams(window.location.search.slice(1)); // myParam=12
In later implementations, you should be able to use it without slice:
var params = new URLSearchParams(window.location.search); // myParam=12
Get
You can get params from it via the .get method:
params.get('myParam'); // 12
Set
Params can be changed using .set:
params.set('myParam', 'newValue');
Output
And if the current querystring is needed again, the .toString method provides it:
params.toString(); // myParam=newValue
There are a host of other methods in this API.
Polyfill
As browser support is still pretty thin, there is a small polyfill by Andrea Giammarchi (<3kB).
Works for me-
function querySt(Key) {
var url = window.location.href;
KeysValues = url.split(/[\?&]+/);
for (i = 0; i < KeysValues.length; i++) {
KeyValue= KeysValues[i].split("=");
if (KeyValue[0] == Key) {
return KeyValue[1];
}
}
}
function GetQString(Key) {
if (querySt(Key)) {
var value = querySt(Key);
return value;
}
}
You can use this Javascript :
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
OR
You can also use the plugin jQuery-URL-Parser allows to retrieve all parts of URL, including anchor, host, etc.
Usage is very simple and cool:
$.url().param("itemID")
via James&Alfa
I have use this method
function getString()
{
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;
}
var buisnessArea = getString();
// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx.
How do I get the dest variable in JavaScript?
Here is a fast and easy way of parsing query strings in 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 (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
Now make a request to page.html?x=Hello:
console.log(getQueryVariable('x'));
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
Turns query string like hello=1&another=2 into object {hello: 1, another: 2}. From there, it's easy to extract the variable you need.
That said, it does not deal with array cases such as "hello=1&hello=2&hello=3". To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits.
You can also use the excellent URI.js library by Rodney Rehm. Here's how:-
var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx
And to parse the query string of current page:-
var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
Me too! http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
Here's my version based loosely on Braceyard's version above but parsing into a 'dictionary' and support for search args without '='. In use it in my JQuery $(document).ready() function. The arguments are stored as key/value pairs in argsParsed, which you might want to save somewhere...
'use strict';
function parseQuery(search) {
var args = search.substring(1).split('&');
var argsParsed = {};
var i, arg, kvp, key, value;
for (i=0; i < args.length; i++) {
arg = args[i];
if (-1 === arg.indexOf('=')) {
argsParsed[decodeURIComponent(arg).trim()] = true;
}
else {
kvp = arg.split('=');
key = decodeURIComponent(kvp[0]).trim();
value = decodeURIComponent(kvp[1]).trim();
argsParsed[key] = value;
}
}
return argsParsed;
}
parseQuery(document.location.search);
Following on from my comment to the answer #bobby posted, here is the code I would use:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:
{
hello: "1",
another: "2",
something: undefined
}
In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:
{
hello: ["1", "2"]
}
You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.
A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)
If you know that you will only have that one querystring variable you can simply do:
var dest = location.search.replace(/^.*?\=/, '');
The following function will parse the search string with a regular expression, cache the result and return the value of the requested variable:
window.getSearch = function(variable) {
var parsedSearch;
parsedSearch = window.parsedSearch || (function() {
var match, re, ret;
re = /\??(.*?)=([^\&]*)&?/gi;
ret = {};
while (match = re.exec(document.location.search)) {
ret[match[1]] = match[2];
}
return window.parsedSearch = ret;
})();
return parsedSearch[variable];
};
You can either call it once without any parameters and work with the window.parsedSearch object, or call getSearch subsequently.
I haven't fully tested this, the regular expression might still need some tweaking...
How about this?
function getQueryVar(varName){
// Grab and unescape the query string - appending an '&' keeps the RegExp simple
// for the sake of this example.
var queryStr = unescape(window.location.search) + '&';
// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');
// Apply RegExp to the query string
var val = queryStr.replace(regex, "$1");
// If the string is the same, we didn't find a match - return false
return val == queryStr ? false : val;
}
..then just call it with:
alert('Var "dest" = ' + getQueryVar('dest'));
Cheers
I wanted a simple function that took a URL as an input and returned a map of the query params.
If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.
This should work back and for with the jQuery.param( qparams ) function.
function getQueryParams(url){
var qparams = {},
parts = (url||'').split('?'),
qparts, qpart,
i=0;
if(parts.length <= 1 ){
return qparams;
}else{
qparts = parts[1].split('&');
for(i in qparts){
qpart = qparts[i].split('=');
qparams[decodeURIComponent(qpart[0])] =
decodeURIComponent(qpart[1] || '');
}
}
return qparams;
};
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.
Page with links: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body
<body onload="replaceLinks()">
Redirect page
Head
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);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body
<body onload="setTimeout('delayer()', 1000)">