基于 window.location.href 的条件 URL 附加或重定向的 Javascript

Win*_*ute 5 javascript url bookmarklet append conditional-statements

我正在尝试制作一个书签,单击该书签时将检查当前选项卡/窗口的 URL,以查看它是否包含“char1”和/或“char2”(给定字符)。如果两个字符都存在,它将重定向到另一个 URL,对于另外两个字符,它将分别附加当前 URL。

我相信一定有一种比下面的更优雅的方式来说明这一点(到目前为止对我来说效果很好),但我对 Javascript 不太了解。我的(笨拙且重复的)工作代码(抱歉):

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');
}
Run Code Online (Sandbox Code Playgroud)

完全符合我的需要,但是,嗯……至少可以说不太优雅。

有没有更简单的方法来做到这一点,也许使用变量或伪对象?或者更好的代码?

And*_*y E 3

对 dthorpe 建议的(某种)重构:

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;
Run Code Online (Sandbox Code Playgroud)

调用assign与为 赋值相同,无论如何,您都在方法中window.location使用加法赋值运算符执行这两项操作:+=

window.location.assign(window.location.href+='append2')
Run Code Online (Sandbox Code Playgroud)

window.location.href这实际上会在调用分配方法之前将“append2”分配到末尾,从而使其变得多余。

您还可以通过设置window.locationvar 来减少 DOM 查找。