Execute function if url does not contain a string from array - javascript

I'm trying run a script if URL doesn't contain specific string. Here is what i have so far:
var ignorePages = ['page1','page2','page3'];
if (window.location.href.indexOf($.inArray(ignorePages)) === -1) {
// do something
}
But this is not working. I would like to test if the string is found in array and if not, execute. Searched the SO Q/A but couldnt find a solution via array using jQuery's inArray.

You can do this easily with underscore. I also think you may want to use location.pathname instead of location.href. Anyhow, this is how I would do it.
import { contains } from 'underscore';
let blacklist = ['/splash', '/login', '/feed' ];
if (! contains(blacklist, window.location.pathname) {
/* do stuff here */
}

Thanks all for pointing in right directions. I've solved it with correct usage of inArray:
var ignorePages = ['/page1','/page2','/page3'];
var currentUrl = window.location.pathname;
if ($.inArray(currentUrl, ignorePages) === -1) {
// do something
}

Related

cleaner way to check whether or not a the current window.location.href is equal to any of the strings in the array

Im trying to do a redirect if the url is equal to any of the strings in the following array of urls:
So I did the following
function redirectUser() {
if (window.location.href === 'https://swish.com/login' || window.location.href === 'https://swish.com/register' || window.location.href === 'https://swish.com/overview') {
window.location.replace('https://swish.com/onboard');
}
}
But this is a bit ugly, so I thought of putting the urls in an array and doing something like this:
function redirectUser() {
const urls = ['https://swish.com/login', 'https://swish.com/register', 'https://swish.com/overview' ]
for(let url of urls) {
if (window.location.href === url) {
window.location.replace('https://swish.com/onboard');
}
}
}
Is there any other way to do this? If not, which would be the better option in your opinion? Thanks!
i think it will help you
function redirectUser() {
const urls = ['https://swish.com/login', 'https://swish.com/register',
'https://swish.com/overview' ]
if(urls.includes(window.location.href)){
window.location.replace('https://swish.com/onboard');
}
}
It appears that you already have all the strings statically within the code. So you can try using switch which performance wise is faster than if check here.
If you are reproducing strings via some logic, then you can also opt for Regular Expressions which is even faster. Else, you can stick with arrays.

split window location accordingly

I am trying to redirect the user according to a lang choice drop down and using their current window.location
So if the user is visiting
xxxx.com will need to go to xxxx.com/langchoice.
2.xxxx.com/currentlang/test.php will need to go to xxxx.com/langchoice/test.php
3 xxxx.com/test.php will need to go to xxxx.com/langchoice/test.php
I have done 1 and 2 but not particularly happy with the way that I coded this considering that if more languages might come I need to add a line every time...can this be rewritten better?
var s = window.location.href;
if (s.indexOf(".php") !=-1)
{
if (s.indexOf("/en/") !=-1)
{
var location=window.location.href.replace("/en/","/"+evt.selectedItem+"/");
}
else if (s.indexOf("/gr/") !=-1)
{
var location=window.location.href.replace("/gr/","/"+evt.selectedItem+"/");
}
else if (s.indexOf("/it/") !=-1)
{
var location=window.location.href.replace("/it/","/"+evt.selectedItem+"/");
}
else
{
}
window.location.replace(location);
}
else
{
var location=window.location.href.replace("#","");
window.location.replace(location+evt.selectedItem);
}
This does make the check to see if there is a "language", but the basic idea to replace would be
There are many ways of doing it, this is one way
var orgPathName = window.location.pathname;
var newPathName = orgPathName.replace(/^\/[^\/]*/,"/" + evt.selectedItem);
var newUrl = window.location.href.replace(orgPathName, newPathName);
Now to do the detection, you do a simple test
var hasLang = (/^\/(en|gr|in)\//i).test(window.location.pathname);
pain with this is maintaining the language list
How do you persist langchoice? Do you store it in a cookie?
I think you are essentially saying that the user should be at:
xxxx.com/[langchoice]etc
at all times.
So you could split on '/' and then, if it exists, check item [1]. If it matches the langchoice cookie, continue, if it doesn't, swap it out.

how to handle JSON.stringify when string is empty

I'm trying to handle an object which doesn't exist in the array.
var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
So, when the javascript code gets here, it fall over because there happens to be nothing in the actual string it is trying to parse. I've tried catching it with "typeof", but that doesn't work either. I'm stumped.
So, the data.flightStatuses[i] array exists, just not the .airportResources.departureGate.
I tried to see if it exists using "typeof data.flightStatuses[i].airportResources.departureGate". It still falls over.
alert (typeof data.flightStatuses[i]) // this comes back "object"
alert (typeof data.flightStatuses[i].airportResources.departureGate) // it dies...
Should be fairly straight forward like this:
if (data.flightStatuses[i].airportResources.departureGate) {
var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
}
It looks like your problem is with airportResources, and not with departureGate.
Try this:
var departureGate = null,
ar = data.flightStatuses[i].airportResources;
if(ar && 'departureGate' in ar){
departureGate = JSON.stringify(ar.departureGate);
}
Cheers
You can check if the departuregate is defined as a property at all like this, and then do the action you wanted, for example:
if(data.flightStatuses[i].airportResources.hasOwnProperty('departureGate') {
var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
} else {
var departuregate = null; // for example
}
More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

javascript - coldfusion - working with a list

This is probably easy for someone.
I am returning a list of campaignIDs (12,45,66) via JSON to a javascript variable
var campaignList = res.DATA.CAMPAIGNS
Now, given a specified campaignID passed in the URL
var campaignId ='<cfoutput>#url.campaignID#</cfoutput>'
I want to check if the returned list contains this campaignID
Any help much appreciated.
Plenty of ways to do it, but I like nice data structures, so ...
Split the list on comma, then loop over list, looking for value:
function campaignExists(campaignList,campaignId) {
aCampaignList = campaignList.split(',');
for (i=0;i<aCampaignList.length;i++) {
if (aCampaignList[i]==campaignId)
return true;
}
return false;
}
Since Array.indexOf sadly isn't cross browser, you're looking at something like:
// assume there is no match
var match_found = false;
// iterate over the campaign list looking for a match,
// set "match_found" to true if we find one
for (var i = 0; i < campaignList.length; i += 1) {
if (parseInt(campaignList[i]) === parseInt(campaignId)) {
match_found = true;
break;
}
}
If you need to do this repeatedly, wrap it in a function
Here's a bit of a "out of the box" solution. You could create a struct for your property id's that you pass into the json searilizer have the key and the value the same. Then you can test the struct for hasOwnProperty. For example:
var campaignIDs = {12 : 12, 45 : 45, 66 : 66};
campaignIDs.hasOwnProperty("12"); //true
campaignIDs.hasOwnProperty("32"); //false
This way if the list is pretty long you wont have to loop through all of the potential properties to find a match. Here's a fiddle to see it in action:
http://jsfiddle.net/bittersweetryan/NeLfk/
I don't like Billy's answer to this, variables within the function have been declared in the global scope and it is somewhat over complicated. If you have a list of ids as a string in your js just search for the id you have from user input.
var patt = new RegExp("(^|,)" + campaignId + "(,|$)");
var foundCampaign = campaignList.search(patt) != -1;

Help refactor a small piece of Javascript code which identifies user's referrer source

I've written the following small piece of javascript (Based on the excellent parseURI function) to identify where the user originated from. I am new to Javascript, and although the code below works, was wondering if there is a more efficient method of achieving this same result?
try {
var path = parseUri(window.location).path;
var host = parseUri(document.referrer).host;
if (host == '') {
alert('no referrer');
}
else if (host.search(/google/) != -1 || host.search(/bing/) != -1 || host.search(/yahoo/) != -1) {
alert('Search Engine');
}
else {
alert('other');
}
}
catch(err) {}
You can simplify the host check using alternative searches:
else if (host.search(/google|bing|yahoo/) != -1 {
I'd also be tempted to test document referrer before extracting the host for your "no referrer" error.
(I've not tested this).
I end up defining a function called set in a lot of my projects. It looks like this:
function set() {
var result = {};
for (var i = 0; i < arguments.length; i++)
result[arguments[i]] = true;
return result;
}
Once you've got the portion of the hostname that you're looking for...
// low-fi way to grab the domain name without a regex; this assumes that the
// value before the final "." is the name that you want, so this doesn't work
// with .co.uk domains, for example
var domain = parseUri(document.referrer).host.split(".").slice(-2, 1)[0];
...you can elegantly test your result against a list using JavaScript's in operator and the set function we defined above:
if (domain in set("google", "bing", "yahoo"))
// do stuff
More info:
http://laurens.vd.oever.nl/weblog/items2005/setsinjavascript/

Categories