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

戏子无情 提交于 2019-12-04 13:46:07

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');}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!