Create RegEx control for URL - javascript

I have a problem with my current web application. Indeed, when I put the current link : https://localhost:44311/#shop, my page displayed perfectly. Here a picture :
But then when I try to change my URL to : https://localhost:44311/#/ , to verify the control of the redirection, the content displayed into the same content, here a picture of what happened :
Currently, all my ajax calls are called again and again and again (an infinite loop).
I'm trying to add control regex for #/, and try to respect #/xxxx/xxxxx. But without success. If you can help me, it could be very nice !
Here my JS where I manage the loadpages :
var ui = {
controller: {
page: {}
},
component: {
category: null
}
};
ui.controller.pageLoad = function (hash = null) {
if (hash === null) {
hash = window.location.hash;
if (hash.length < 2 || hash[0] !== "#") {
hash = "/shop";
}
} else if (hash.length < 2 || hash[0] === "#" && hash[1] === '/') { // add control regex for #/, must respect #/xxxx/xxxxx
hash = "/shop";
}
$.get(hash.substring(1), function (data) {
ui.controller.page = null;
$("#content").html(data);
}).fail(function (error) {
$.get("/Home/Error?status=" + error.status, function (data) {
ui.controller.page = null;
$("#content").html(data);
});
});
};

You could create a isValidHash function, and use it in your if statement:
function isValidHash(hash) {
return typeof hash === "string" && /^#(\/[a-z0-9-]+)+$/.test(hash);
}
function test(v) {
console.log(`'${v}' is ${isValidHash(v) ? '' : 'NOT '}valid`);
}
test(null); // NO - not a string
test('#'); // NO - too short
test('#shop'); // NO - no slash
test('#/shop'); // YES
test('#/shop/item-9'); // YES

Related

How to maintain browser history while doing a location.reload() on popstate event of Javascript

So, I have a scenario where I am generating all my URL's using history.pushState function. I am NOT using any server side technique for this. I am fetching all the data only once from the server and then generating the URL using Javascript.
Now the problem that I am encountering is using the popstate function which basically mimics the back button behavior of a browser.
Everything is working fine for ONLY one back button click.
$(window).on('popstate', function (event) {
location.reload(true);
//window.location.href = document.location;
//console.log("location: " + document.location);
});
After one back button event, I am unable to see any previous history of the browser. I am assuming it is happening because of location.reload method. I tried storing all my location also and then doing a redirect but same thing, the browser history gets lost after one refresh.
Is there a way where I can achieve this without the browser losing it's history for multiple back button clicks?
If there is a JQuery option for this, then it would be great if someone could share their knowledge on this aspect.
I wrote a simple plugin built around the History API that I use in my projects. It will do what you are asking.
// instantiate the QueryString Class.
qsObj=new QueryString({
onPopstate: function(qsParams, data, dataAge, e) {
// This function is called on any window.popstate event
// -- triggered when user click browser's back or forward button.
// -- triggered when JS manipulates history.back() or history.forward()
// -- NOT triggered when any of the QueryString methods are called (per the native behavior of the HTML5.history API which this class uses.)
// -- Might be triggered on page load in some browsers. You can handle this by checking for the existence of data, eg: if(data){ 'do something with the data' }else{ 'move along nothing to do here' }
console.log('executing onPopstate function');
console.log('page query string parameters are: ', qsParams);
console.log('stored page data is: ', data);
console.log('dataAge is:', dataAge, ' seconds old');
// do stuff..
if(data) {
if(dataAge && dataAge<=20) {
// use the stored data..
} else {
// it's old data get new..
}
} else {
// the current page has no stored data..
}
},
onDocumentReady: function(qsParams) {
// Document ready is only called when a page is first browsed to or the page is refreshed.
// Navigating the history stack (clicking back/forward) does NOT refire document ready.
// Use this function to handle any parameters given in the URL and sent as an object of key/value pairs as the first and only parameter to this function.
console.log('executing onDocumentReady function');
console.log('page query string parameters are:',qsParams);
// do stuff..
}
});
Plugin Usage:
// == QueryString class =============================================================================================
//
// Modifies the query string portion of a browsers URL, updates the browsers history stack - saving page data
// along with it, all without reloading the page.
// Can be used to simply obtain querystring parameter values as well.
//
// == Instantiate: ================================
//
// var qsObj=new QueryString(
//
// onPopstate: function(qsParams, data, dataAge, e) {
//
// // This function is called on any window.popstate event
// // -- triggered when user click browser's back or forward button.
// // -- triggered when JS manipulates history.back() or history.forward()
// // -- NOT triggered when any of the QueryString methods are called (per the native behavior of the
// // HTML5.history API which this class uses.)
// // -- Might be triggered on page load in some browsers. You can handle this by checking for the
// // existence of data, eg:
// // if(data){ 'do something with the data' }else{ 'move along nothing to do here' }
//
// // -- qsParams: is an object that contains the current pages query string paramters as key:value pairs.
// // -- data: is an object that contains any page data that was stored at the time that this page was added
// // to the history stack via this class (or any HTML5 history API method), otherwise this value is NULL!
// // -- dataAge: null if data is null or the page data was not added via the methods in this class,
// // otherwise the value is the age of the data in seconds.
// // -- e: the event object if you want it.
//
// if(data){
// if(dataAge && dataAge <= 600){ // do it this way otherwise you'll error out if dataAge is null.
// // There is data and it is less than 10 minutes old.
// // do stuff with it..
// }
// }
// },
//
// onDocumentReady: function(qsParams){
// // Document ready is only called when a page is first browsed to or the page is refreshed.
// // Navigating the history stack (clicking back/forward) does NOT refire document ready.
// // Use this function to handle any parameters given in the URL and sent as an object of key/value pairs as
// // the first and only parameter to this function.
//
// // do stuff with any qsParams given in the URL..
//
// }
//
// });
//
//
// == The following methods are available: =======================================
//
//
// var qsParams = qsObj.parseQueryString(); // returns an object that contains the key/value pairs of all the query
// // string parameter/values contained in the current URL, or an empty object
// // if there are none.
//
//
// qsObj.update({
//
// // Use this method to add/remove query string parameters from the URL and at the same time update, or add to, the
// browser history stack with the ability to also save page data in with the history.
//
// opType: 'auto',
// // -- Optional. Allowed values: ['replace'|'push'|'auto'], Default is 'auto' unless 'push' or 'replace' is
// // specifically given.
// // -- 'push': Adds the new URL and any page data onto the browser history stack.
// // -- 'replace': Overwrites the current page history in the stack with the new URL and/or page data
// // -- 'auto': compares the initial qs parameters with the updated qs parameters and if they are the same
// // does a 'replace', if they are different does a 'push'.
//
// qsParams: {
// hello: 'world',
// another: 'pair'
// },
// // -- Optional. Object that contains key/value pairs to add to the query string portion of the URL.
// // -- Will entirely replace what is/isn't currently in the query string with the given key/value pairs.
// // -- The parameters contained in the url querystring will be made, or unmade, based on the key/value pairs
// // included here so be sure to include all of the pairs that you want to show in the URL each time.
//
//
// data: {
// key1: 'value1',
// key2: 'value2'
// }
// // Optional, Object that contains key/value pairs to store as page data in the browser history stack for this page.
//
// // ** If qsParams and data are ommitted then nothing silently happens. (This is not the same as given but empty,
// // in which case something happens.)
//
// });
//
//
// qsObj.Clear({
//
// // Use this method to remove all query string parameters from the URL and at the same time update, or add to, the
// // browser history stack with the ability to also save page data in with the history.
//
// optype: 'auto' // optional, defaults to auto.
//
// data: {} // Optional, defaults to empty object {}.
// });
//
// =========================================================================================================================
Plugin Code:
; (function () {
var Def = function () { return constructor.apply(this, arguments); };
var attr = Def.prototype;
//== list attributes
attr.popstateCallback = null;
attr.docreadyCallback = null;
attr.skipParseOnInit = false;
attr.currentQS;
//== Construct
function constructor(settings) {
if (typeof settings === 'object') {
if ('onPopstate' in settings && typeof settings.onPopstate === 'function') {
this.popstateCallback = settings.onPopstate;
}
if ('onDocumentReady' in settings && typeof settings.onDocumentReady === 'function') {
this.docreadyCallback = settings.onDocumentReady;
}
}
if (this.skipParseOnInit !== true) {
this.currentQS = this.parseQueryString();
}
var self = this;
if (typeof this.popstateCallback === 'function') {
$(window).on('popstate', function (e) {
var data = null;
var dataAge = null;
if (typeof e === 'object' && 'originalEvent' in e && typeof e.originalEvent === 'object' && 'state' in e.originalEvent && e.originalEvent.state && typeof e.originalEvent.state === 'object') {
data = e.originalEvent.state;
if ('_qst_' in data) {
dataAge = ((new Date).getTime() - e.originalEvent.state['_qst_']) / 1000; // determine how old the data is, in seconds
delete data['_qst_'];
}
}
var qsparams = self.parseQueryString();
self.popstateCallback(qsparams, data, dataAge, e);
});
}
if (typeof this.docreadyCallback === 'function') {
$(document).ready(function () {
self.docreadyCallback(self.currentQS);
});
}
}
//== Define methods ============================================================================
attr.parseQueryString = function (url) {
var pairs, t, i, l;
var qs = '';
if (url === undefined) {
var loc = window.history.location || window.location;
qs = loc.search.replace(/^\?/, '');
} else {
var p = url.split('?');
if (p.length === 2) {
qs = p[1];
}
}
var r = {};
if (qs === '') {
return r;
}
// Split into key/value pairs
pairs = qs.split("&");
// Convert the array of strings into an object
for (i = 0, l = pairs.length; i < l; i++) {
t = pairs[i].split('=');
var x = decodeURI(t[1]);
r[t[0]] = x;
}
return r;
};
//-- Get a querystring value from it's key name
attr.getValueFromKey = function (key) {
var qs = this.parseQueryString();
if (key in qs) {
return decodeURIComponent(qs[key].replace(/\+/g, " "));
} else {
return null;
}
};
//-- if urlValue is given then qsParams are ignored.
attr.update = function (params) {
if (typeof params !== 'object') { return; }
var urlValue = null;
var data = {};
if ('data' in params) {
data = params.data;
urlValue = '';
}
var opType = 'opType' in params ? params.opType : 'auto';
if ('urlValue' in params && typeof params.urlValue === 'string') {
urlValue = params.urlValue;
if (opType === 'auto') {
var loc = window.history.location || window.location;
if (loc.protocol + '//' + loc.host + loc.pathname + loc.search === urlValue || loc.pathname + loc.search === urlValue) {
opType = 'replace'; // same URL, replace
} else {
opType = 'push'; // different URL, push
}
}
} else if ('qsParams' in params && typeof params.qsParams === 'object') {
var pairs = [];
for (var key in params.qsParams) {
pairs.push(key + '=' + params.qsParams[key]);
}
urlValue = '?' + pairs.join('&', pairs);
if (opType === 'auto') {
if (this.compareQsObjects(params.qsParams, this.currentQS) === false) { // different
this.currentQS = params.qsParams;
opType = 'push';
} else { // same
opType = 'replace';
}
}
}
this.replaceOrPush(urlValue, data, opType);
};
//== Add querystring
//-- just an alias to update
attr.add = function (params) {
return this.update(params);
};
//== Remove specified querystring parameters
// -- Use clear() method to remove ALL query string parameters
attr.remove = function (params) {
var urlValue = null;
var qsChanged = false;
if ('qsParams' in params && params.qsParams.length > 0) {
var qs = this.parseQueryString();
var key;
for (var i = 0, l = params.qsParams.length; i < l; ++i) {
key = params.qsParams[i];
if (key in qs) {
delete qs[key];
qsChanged = true;
}
}
}
if (qsChanged === true) {
var pairs = [];
for (key in qs) {
pairs.push(key + '=' + qs[key]);
}
urlValue = '?' + pairs.join('&', pairs);
var data = 'data' in params ? params.data : {};
var opType = 'opType' in params ? params.opType : '';
this.replaceOrPush(urlValue, data, opType);
}
return;
};
//== Delete querystring
//-- just an alias to remove
attr.delete = function (params) {
return this.remove(params);
};
//== Removes all query string parameters.
// Use remove() method to remove just the given parameters
attr.clear = function (params) {
params = typeof params === 'undefined' ? {} : params;
var urlValue = window.history.location || window.location;
urlValue = urlValue.protocol + '//' + urlValue.host + urlValue.pathname;
var data = 'data' in params ? params.data : {};
var opType = 'opType' in params ? params.opType : '';
this.replaceOrPush(urlValue, data, opType);
return;
};
//== Simple wrapper to the HTML5 history API's replaceState() method.
// --also used internally
attr.replaceState = function (urlValue, data) {
if (typeof urlValue !== 'string') {
return;
}
if (typeof data !== 'object') {
data = {};
}
data['_qst_'] = (new Date).getTime(); // store a timestamp value
history.replaceState(data, '', urlValue);
};
//== Simple wrapper to the HTML5 history API's pushState() method.
// --also used internally
attr.pushState = function (urlValue, data) {
if (typeof urlValue !== 'string') {
return;
}
if (typeof data !== 'object') {
data = {};
}
data['_qst_'] = (new Date).getTime(); // store a timestamp value
history.pushState(data, '', urlValue);
};
//-- internal use - simple gatekeeper to decide if there is anything to do and will default to 'replace' opType if this value is not given.
attr.replaceOrPush = function (urlValue, data, opType) {
// is there anything to do?
if (typeof urlValue === 'string' || typeof data === 'object') {
// yes, what type of operation are we going to do?
if (opType === 'push') {
this.pushState(urlValue, data);
} else {
this.replaceState(urlValue, data);
}
}
return;
};
// == internal use - compares the existing qs with a potentially updated one to see if they are the same (returns true) or not (returns false)
attr.compareQsObjects = function (a, b) {
if (typeof a === 'object' && typeof b === 'object') {
var aa = [];
var bb = [];
for (k in a) {
aa.push(k + a[k]);
}
aa.sort();
for (k in b) {
bb.push(k + b[k]);
}
bb.sort();
if (aa.join('') !== bb.join('')) { return false; }
return true;
}
return null;
};
//unleash your class
window.QueryString = Def;
})();
Well, this is not really possible.
The only trick I'm thinking about is to change window.location.href when the popstate event is fired, and to pass your history as URL parameters.
$(window).on('popstate', function (event) {
window.location.href = 'https://here.com?history = ' + yourHistory;
});
You need to figure out how you can send your history with this method, and handle it when you arrive on the new page to be able to send it again when the user clicks back button again.
You also have to make sure the URL generated is not too long.

JavaScript - use link parameter to create text in the H1 tag of another page

In this example I have two pages - 1 product page, and 1 conversion page.
On the product page I will have a link that points to the conversion page. On this link I would like to pass the product name via a parameter. something like this: href = conversionpage.html?productName
On the conversion page I would like use JavaScript to take the product name parameter and populate the h1 tag - so the h1 tag would be something like this < h1 >productName< /h1 >
Make sense? I have no idea how to do this.
Thank you in advance for your help. I have 100,000 + product pages this example was just to simplify the issue.
Here is what I think you want to do.
Get the URL search parameters, then take the one you need and place it in the innerHTML of the desired tag.
Loops = function(collection, fn) {
'use strict';
var i;
if ((collection.item && collection.length) || collection instanceof Array || collection instanceof Element || collection.elements || collection.jquery) {
i = collection.length;
if (i > -1) {
do {
if (collection[i] !== undefined) {
fn(i);
}
} while (--i >= 0);
}
return this;
} else {
throw new Error('"collection" (' + collection + ') is not valid. It should be an array or have an "item" method and a "length" property');
}
};
GetURLParameters = function(keys) {
'use strict';
var pair, arr, query, parameters, queryString;
if (location.search) {
query = location.search.substring(1);
parameters = query.split("&");
queryString = {};
}
function createObject(key, val, i) {
pair = parameters[i].split("=");
if (typeof queryString[pair[key]] === "undefined") {
queryString[pair[key]] = decodeURI(pair[val]);
} else if (typeof queryString[pair[key]] === "string") {
arr = [queryString[pair[key]], pair[val]];
queryString[pair[key]] = arr;
} else {
queryString[pair[key]].push(pair[val]);
}
}
if (parameters && keys === 1) {
Loops(parameters, function(i) {
createObject(1, 0, i);
});
} else if (parameters) {
Loops(parameters, function(i) {
createObject(0, 1, i);
});
}
return queryString;
};
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
var params = GetURLParameters();
console.log(params);
document.getElementById('h1').innerHTML = params['parameter-name'];
<h1 id="h1"></h1>
with a url of http://example.com?productName=Walkman
<body>
<h1 id="productName"></h1>
</body>
<script type='text/javascript'>
// start by creating a function
function loadUp(){
var str = window.location.search.replace(/(?:(\D+=))/ig, "") //get the search parameters from the url and remove everything before the "=" sign
document.getElementById('productName').innerHTML = str //assign that string to the "innerHTML" of the h1 tag that has an id of "productName"
};
window.onload = loadUp; // once the page has loaded, fire off that function
</script>
this script will do this once the document has been loaded:
<body>
<h1 id="productName">Walkman</h1>
</body>

Refreshing a webpage is actually redirecting to bing

I have a script, in which I am adding custom URL to the browser back button
for this I used this particular script
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript" src="js/native.history.js"></script>
<script type="text/javascript" src="js/go.new.js"></script>
<script>
$(window).load(function()
{
setTimeout(backtrap, 100);
if (!($.cookie("clkd"))){
$.cookie("clkd", 1, { expires : 14 , path: '/'});
}
setInterval(toggle_image, 1000);
});
window.onpageshow = function (e) {
if (e.persisted) {
location.reload();
}
};
window.onpopstate = function(event) {
if (document.location.toString().indexOf("redir=1")>0){
window.location.href = "<?=$$last_offer?>";
//window.location.href = "<?=$szLinkURL?>";
}
};
function toggle_image()
{
var height = $('#banner-img').height();
$('#banner-img').toggle();
$('#loader-img').toggle();
$('#loader-img').css({'height':height+'px'});
}
function show_star(rate,id)
{
$('#al-stars-'+id).html('<span class="stars" id="stars-'+id+'">'+parseFloat(rate)+'</span>');
$('#stars-'+id).stars();
}
$.fn.stars = function()
{
return $(this).each(function() {
$(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
});
}
</script>
Now the script seems to work fine, but I face a new proble, that is:
when I am clicking the refresh button on the browser, the page is rediecting to bing.com
but I dont know why this is happening...
in case if needed here's the script in the go.new.js
/**
* go.js
*
* Functions for go.php and the backtrap
*/
// --------------------------------------------------------------------------------------------------------------------
// Code for parsing query string gratefully lifted from http://unixpapa.com/js/querystring.html, with an
// addition for modifying/generating new query strings.
// Query String Parser
//
// qs= new QueryString()
// qs= new QueryString(string)
//
// Create a query string object based on the given query string. If
// no string is given, we use the one from the current page by default.
//
// qs.value(key)
//
// Return a value for the named key. If the key was not defined,
// it will return undefined. If the key was multiply defined it will
// return the last value set. If it was defined without a value, it
// will return an empty string.
//
// qs.values(key)
//
// Return an array of values for the named key. If the key was not
// defined, an empty array will be returned. If the key was multiply
// defined, the values will be given in the order they appeared on
// in the query string.
//
// qs.keys()
//
// Return an array of unique keys in the query string. The order will
// not necessarily be the same as in the original query, and repeated
// keys will only be listed once.
//
// QueryString.decode(string)
//
// This static method is an error tolerant version of the builtin
// function decodeURIComponent(), modified to also change pluses into
// spaces, so that it is suitable for query string decoding. You
// shouldn't usually need to call this yourself as the value(),
// values(), and keys() methods already decode everything they return.
//
// Note: W3C recommends that ; be accepted as an alternative to & for
// separating query string fields. To support that, simply insert a semicolon
// immediately after each ampersand in the regular expression in the first
// function below.
function QueryString(qs)
{
this.dict= {};
// If no query string was passed in use the one from the current page
if (!qs) qs= location.search;
// Delete leading question mark, if there is one
if (qs.charAt(0) == '?') qs= qs.substring(1);
// Parse it
var re= /([^=&]+)(=([^&]*))?/g;
while (match= re.exec(qs))
{
var key= decodeURIComponent(match[1].replace(/\+/g,' '));
var value= match[3] ? QueryString.decode(match[3]) : '';
if (this.dict[key])
this.dict[key].push(value);
else
this.dict[key]= [value];
}
}
QueryString.decode= function(s)
{
s= s.replace(/\+/g,' ');
s= s.replace(/%([EF][0-9A-F])%([89AB][0-9A-F])%([89AB][0-9A-F])/g,
function(code,hex1,hex2,hex3)
{
var n1= parseInt(hex1,16)-0xE0;
var n2= parseInt(hex2,16)-0x80;
if (n1 == 0 && n2 < 32) return code;
var n3= parseInt(hex3,16)-0x80;
var n= (n1<<12) + (n2<<6) + n3;
if (n > 0xFFFF) return code;
return String.fromCharCode(n);
});
s= s.replace(/%([CD][0-9A-F])%([89AB][0-9A-F])/g,
function(code,hex1,hex2)
{
var n1= parseInt(hex1,16)-0xC0;
if (n1 < 2) return code;
var n2= parseInt(hex2,16)-0x80;
return String.fromCharCode((n1<<6)+n2);
});
s= s.replace(/%([0-7][0-9A-F])/g,
function(code,hex)
{
return String.fromCharCode(parseInt(hex,16));
});
return s;
};
QueryString.prototype.value= function (key)
{
var a= this.dict[key];
return a ? a[a.length-1] : undefined;
};
QueryString.prototype.values= function (key)
{
var a= this.dict[key];
return a ? a : [];
};
QueryString.prototype.keys= function ()
{
var a= [];
for (var key in this.dict)
a.push(key);
return a;
};
QueryString.prototype.set = function(key, value)
{
this.dict[key] = [value];
};
QueryString.prototype.add = function(key, value)
{
if (typeof this.dict[key] == 'undefined') {
this.dict[key] = [value];
} else {
this.dict[key].push(value);
}
};
QueryString.prototype.toString = function()
{
var pieces = [];
for (var key in this.dict) {
for (var idx in this.dict[key]) {
pieces.push( encodeURIComponent(key) + '=' + encodeURIComponent(this.dict[key][idx]));
}
}
return pieces.join('&');
};
// --------------------------------------------------------------------------------------------------------------------
// Load ourselves into the user's history, with an altered query string. The 'bt' var tells us what step of the
// back trap we were LAST on. After that, we redirect ourselves to the next URL.
function backtrap() {
var qs = new QueryString();
qs.set('redir', 1);
var own_url = window.location.href;
var qs_at = own_url.indexOf('?');
var doped_url;
if (qs_at == -1) {
doped_url = own_url + '?' + qs.toString();
} else {
doped_url = own_url.substring(0, qs_at) + '?' + qs.toString();
}
History.pushState({}, '', doped_url);
History.pushState({} ,'', own_url);
alert(doped_url);
alert(own_url);
}
for better understanding
check this link and detect
http://gomotrak.com/main/click.php?c=2173&key=jm64njqpq608t19bgqi3fwfq&c2=AA09_00000&c3=[zone]
[NOTE]
The backbutton is working fine, there is no issue with the back-button...
Problem is, when i am clicking on the refresh button of the browser in the address bar, its reloading the bing page.
Also $$last_offer is absolutely fine cause its working this way
if(stripos($ua,'android') !== false)
{
$agent = 'a';
setlocale(LC_ALL, 'pt_BR.UTF-8');
$last_CSVfp = fopen("offer_android.csv", "r");
$last_offer_data = array();
if($last_CSVfp !== FALSE)
{
while(! feof($last_CSVfp))
{
$last_offer_data[] = fgetcsv($last_CSVfp,"",",");
}
}
fclose($last_CSVfp);
$last_arr_size = count($last_offer_data);
$last_offer = "offer".intval(intval($last_arr_size)+1);
}
so $last_offer becomes "offer3" for example
and $$last_offer becomes "$offer3" its like alias of a phpvariabledenoted by anotherphp variable`

What location.hash.match return if there is no hash?

please can you tell me what does location.hash.match return if there is no hash ?
My code :
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
test = getHashValue('test');
if (test == 'abc') {
//code WORKS
}
else if (test == 'sal') {
//code WORKS
}
else if (test == "") {
//code DOESNT WORKS
}
but It doesn't works
I forget to mentionned that my code 'getHashValue' return the value of the hash Exemple : #test=abc
sorry I forget to mentionned it
Why not just?
test = getHashValue('test');
if (test === undefined) {
//code
}
EDIT
The error was from a null return in the match() call. The following change will return an empty string if the match is "" or null.
function getHashValue(key) {
var match = location.hash .match(new RegExp(key + '=([^&]*)'));
return match ? match[1] : "";
}
If you run location.hash in your browser console on any website where you're not using a hash, you'll find that it returns the empty string "".
As such, a regex match on that will find 0 results, returning null, at which point, you try to access null[1]...
location.hash will be empty string and your function:
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
Will indeed return undefined. The problem is that you are checking "undefined" value incorrectly. Change your code to:
test = getHashValue('test');
if (typeof(test) === 'undefined') {
//code
}

Javascript for conditional URL append or redirect based on window.location.href

I am trying to make a bookmarklet that when clicked will check the URL of the current tab/window to see if it contains 'char1' and/or 'char2' (a given character). If both chars are present it redirects to another URL, for the other two it will append the current URL respectively.
I believe there must be a more elegant way of stating this than the following (which has so far worked perfectly for me) but I don't have great knowledge of Javascript. My (unwieldy & repetitive) working code (apologies):
if (window.location.href.indexOf('char1') != -1 &&
window.location.href.indexOf('char2') != -1)
{
window.location="https://website.com/";
}
else if (window.location.href.indexOf('char1') != -1)
{
window.location.assign(window.location.href += 'append1');
}
else if (window.location.href.indexOf('char2') != -1)
{
window.location.assign(window.location.href += 'append2');
}
Does exactly what I need it to but, well... not very graceful to say the least.
Is there a simpler way to do this, perhaps with vars or a pseudo-object? Or better code?
A (sort-of) refactoring of dthorpe's suggestion:
var hasC1 = window.location.href.indexOf('char1')!=-1
var hasC2 = window.location.href.indexOf('char2')!=-1
var newLoc = hasC1
? hasC2 ? "https://website.com/" : window.location.href+'append1'
: hasC2 ? window.location.href+'append1' : '';
if (newLoc)
window.location = newLoc;
Calling assign is the same as assigning a value to window.location, you were doing both with the addition assignment += operator in the method anyway:
window.location.assign(window.location.href+='append2')
This would actually assign "append2" to the end of window.location.href before calling the assign method, making it redundant.
You could also reduce DOM lookups by setting window.location to a var.
The only reduction I can see is to pull out the redundant indexof calls into vars and then test the vars. It's not going to make any appreciable difference in performance though.
var hasChar1 = window.location.href.indexOf('char1') != -1;
var hasChar2 = window.location.href.indexOf('char2') != -1;
if (hasChar1)
{
if (hasChar2)
{
window.location="https://website.com/";
}
else
{
window.location.assign(window.location.href+='append1');
}
}
else if (hasChar2)
{
window.location.assign(window.location.href+='append2');
}
Kind of extendable code. Am i crazy?
var loc = window.location.href;
var arr = [{
url: "https://website.com/",
chars: ["char1", "char2"]
}, {
url: loc + "append1",
chars: ["char1"]
}, {
url: loc + "append2",
chars: ["char2"]
}];
function containsChars(str, chars)
{
var contains = true;
for(index in chars) {
if(str.indexOf(chars[index]) == -1) {
contains = false;
break;
}
}
return contains;
}
for(index in arr) {
var item = arr[index];
if(containsChars(loc, item.chars)) {
window.location.href = item.url;
break;
}
}
var location =window.location.href
if (location.indexOf('char1')!=-1 && location.indexOf('char2')!=-1)
{window.location="https://website.com/";}
else if (location.href.indexOf('char1')!=-1) {window.location.assign(location+='append1');}
else if (location.indexOf('char2')!=-1) {window.location.assign(location+='append2');}

Categories

Resources