Given the following URL:
https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States
How can I save three vars:
var date1: "2015";
var date2: "2017";
var loc = "United States";
Note: we have two dates with a + symbol in the url 2015+2017 and we need to split them. And has a dash in the url United-States and we need it as United States
This is what I am trying:
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;
}
var dates = getUrlVars()["usp-custom-14"];
var loc = getUrlVars()["usp-custom-8"];
var dateSplit = dates.split("+");
Also, I need to update the URL again for other reasons once the page is loaded, and I do:
history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14='+dateSplit+'&usp-custom-8='+loc);
But the url is duplicated
https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States/?usp-custom-14=2015,2017&usp-custom-8=United-States
You can split the url on ? and use pop() to return the last member of the resulting array, which would be the entirety of your query string.
From there, you could split it into key-value pairs by splitting it first on &, and then on =.
I've put this in a function so that you can simply do getParam("my-url-parameter") when needed. Using this, and then handling the + and - on your specific parameters, you should be able to get what you want quite easily.
It should also be reusable wherever needed.
function getParam(key) {
//var url = window.location.href; (Doesn't work on StackOverflow, but would be used in your real environment)
var url = "https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States";
var querystring = url.split("?").pop();
var params = {};
querystring.split("&").forEach((i) => params[i.split("=")[0]] = i.split("=")[1]); //Create key-value pairs
return params[key] || null;
}
var uspCustom14 = getParam("usp-custom-14").split("+");
var date1 = uspCustom14[0];
var date2 = uspCustom14[1];
var country = getParam("usp-custom-8").replace(/\-/g, ' ');
console.log(`Date 1: ${date1},`, `Date 2: ${date2},`, `Country: ${country}`);
For your second issue, you can remove the query string and re-add it with the proper values:
var urlDates = getParam("usp-custom-14").replace('+',',');
var urlCountry = getParam("usp-custom-8");
history.replaceState('data to be passed', 'Title of the page', `${window.location.href.split("?")[0]}?usp-custom-14=${urlDates}&usp-custom-8=${urlCountry}`);
This should give you what you want while keeping it as close to your original code as I could. You can safely split a string with a "+" in it. You had the "?" and "=" splits in the wrong order.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.split('?')[1];
var params = hashes.split('&');
for(var i = 0; i < params.length; i++) {
hash = params[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var dates = getUrlVars()["usp-custom-14"];
var loc = getUrlVars()["usp-custom-8"];
var dateSplit = dates.split("+");
var str ="https://example.com/test/results/?usp-custom-14=2015+2017&usp-custom-8=United-States";
var split = str.split('usp-custom-14=');
var firstDate = split[1].split('+')[0];
var secondDate = split[1].substring(split[1].lastIndexOf("+")+1,split[1].lastIndexOf('&'));
var country = split[1].substring(split[1].lastIndexOf("=")+1,split[1].length-1).replace('-',' ');
console.log(firstDate);
console.log(secondDate);
console.log(country);
Related
I'm trying to generate a UserID out of userAgent and Date Function. I also wanted to understand callback function (which I still didn't get (JS Noob)). Therefore I built the following example:
var storage = window.localStorage;
var storageUserId = storage.getItem("userID");
var text = "";
function userID(callback){
var agent = window.navigator.userAgent;
var now = new Date();
try{
callback(agent, now);
}catch(e){}
}
function hasher(agent,now){
var hash = 0;
var arr = [];
for(var i = 0; i < arguments.length; i++){
var pars = arguments[i];
for(var j = 0; j < pars.length; j++){
var charI = pars.charCodeAt(j);
hash = ((hash<<5)-hash)+charI;
hash = hash & hash; // Convert to 32bit integer
hash = hash.toString();
}
}
console.log(hash + "|" + hash);
}
userID(hasher);
The result should look like this "9834917834|8293479273" (example numbers to show format). First number hashed agent second number hashed date. I got the hash logic form here: http://mediocredeveloper.com/wp/?p=55
Maybe there is a better way to do this :)
I really appreciate your help!
Thanks a lot!
Best,
Anton
You should extract the hashing loop into a new function:
function hash(str){
var hash = 0;
for(const char of str){
const charCode = char.charCodeAt(0);
hash = ((hash<<5)-hash)+charCode;
}
hash = hash & hash; // Convert to 32bit integer
return hash.toString();
}
So to get the hash you want to you just need to call it twice:
function getUserID(){
return hash(window.navigator.userAgent) + "|" + hash("" + new Date);
}
(PS: you know that new Date will change every millisecond?)
I have a URL like:
http://www.mysite.com/index.html?x=x1&x=x2&x=x3
How do I got the values like below, using JavaScript or JQuery:
var x='x1,x2,x3'
var url = "http://www.mysite.com/index.html?x=x1&x=x2&x=x3";
var params = url.match(/\?(.*)$/)[1].split('&');
var values = [];
for(var i=0; i<params.length; i++){
values.push( params[i].match(/=(.*)$/)[1] );
}
var result = values.join(","); // "x1,x2,x3"
EDIT: Here is a better solution that lets you select the parameter you want. This is something that I have found buried inside one of my projects, and I didn't write every part of it.
function $_GET(param) {
var query = window.location.search.substring(1);
var vars = query.split('&');
var values = [];
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (urldecode(pair[0]) == param) {
values.push(urldecode(pair[1]));
}
}
return values.join(",");
}
// Decode URL with the '+' character as a space
function urldecode(url) {
return decodeURIComponent(url.replace(/\+/g, ' '));
}
If you directly hit url you can use it as
var fieldValue = ['x1','x2','x3'];
var searchValue = 'x='+ fieldValue.join(',');
window.location.search = searchValue;
This will hit current url to search data for given parameters.
If you want to manually create url then hit search then
var url = "http://www.mysite.com/index.html";
window.location.href = url;
var fieldValue = ['x1','x2','x3'];
var searchValue = 'x='+ fieldValue.join(',');
window.location.search = searchValue;
Now you can search values, as per requirement.
I think what you need is PURL. Please refer https://github.com/allmarkedup/purl for detailed usage and guidelines
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] == VarSearch){
return KeyValuePair[1];
}
}
}
read here http://javascriptproductivity.blogspot.in/2013/02/get-url-variables-with-javascript.html
You can easily find query string in jquery using jquery split
Try this function to get Query String as a array object:
function getUrlVars()
{
var vars = [];
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[1]);
}
return vars;
}
The function returns an array/object with your URL parameters and their values. So, you can use jquery .join() to convert it into comma separated values:
var result = vars.join(",");
Try in jsfiddle
Maybe use Regex:
var s = window.location.search;
var foo = s.match(/x=([0-9a-zA-Z]+)/g).join(",").replace(/x=/g, ""); // x1,x2,x3
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.
I'm trying to return c= and then have it write into an input field and the submit the value.
var x = window.external.menuArguments.location.href; // IE Get URL Code
alert(x);
// http://site.com/design/page.html?c=235783&p=irol-IRHome
// this code below populates a html pop that is created on popup.
var parentwin = external.menuArguments;
var doc = parentwin.document;
var sel = doc.selection;
var rng = sel.createRange();
var str = new String(rng.text);
var html = new String(rng.htmlText);
var ops = "width=650,height=410,status=0,toolbar=0,menubar=0,resizable=1";
viewSourceWin = parentwin.open("about:blank","viewselectionscr",ops);
// open document for further output
viewSourceWin.document.open();
viewSourceWin.document.write("$(document).ready(function() {");
viewSourceWin.document.write("load = ?;");
viewSourceWin.document.write("$('#cmid').val(load);$('.go').click();");
viewSourceWin.document.write("});");
viewSourceWin.document.write("<input id='cmid'/><button class='go'>Go</button>")");
You want the location.search, like:
var query = window.location.search.substring(1); // use substring to remove the leading '?'
var keyValues = query.split('&'); // split apart
var params = {};
for (var kv in keyValues) {
var parts = kv.split('=');
params[ parts[0] ] = parts[1];
}
var c = params['c'];
//... do whatever you need
Of course there is a jquery plugin or three and some fancier regular expressions that you could also use.
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"