使用正则表达式优化switch网站切换逻辑时遇语法错误的问题
书签脚本语法错误分析及修正方案
错误原因拆解
函数参数定义非法
你写的function toggle(location.host)是错误的,JavaScript函数参数只能是合法变量名,不能是location.host这种带属性访问的表达式,这是触发语法错误的直接原因。switch case条件逻辑错误
用switch(true)时,每个case必须是布尔表达式,但你写的case 'github.com':是字符串值,不是判断语句;正则匹配部分错误使用了.toggle(str)方法,正则判断应该用.test(),而且str未定义,需要传入要检测的host值。URL替换逻辑存在bug
url.replace('/.+/', 'www.reddit.com')是把字符串"/.+/"替换成目标域名,而非用正则匹配域名部分,会导致替换完全不符合预期。
修正后的代码
function toggleSite() { const host = location.host; let url; switch (true) { case host === 'github.com': url = location.href.replace('github.com', 'stackoverflow.com'); window.open(url, '_self'); break; case host === 'stackoverflow.com' || host === 'superuser.com' || /.+\.stackexchange\.com$/.test(host): // 精准匹配域名部分,保留原路径和参数 url = location.href.replace(/^https?:\/\/[^\/]+/, 'https://www.reddit.com'); window.open(url, '_self'); break; case host === 'www.reddit.com': url = location.href.replace('www.reddit.com', 'github.com'); window.open(url, '_self'); break; } } toggleSite();
书签脚本适配版(可直接导入书签)
javascript:(()=>{const h=location.host;let u;switch(true){case h==='github.com':u=location.href.replace('github.com','stackoverflow.com');break;case h==='stackoverflow.com'||h==='superuser.com'||/.+\.stackexchange\.com$/.test(h):u=location.href.replace(/^https?:\/\/[^\/]+/,'https://www.reddit.com');break;case h==='www.reddit.com':u=location.href.replace('www.reddit.com','github.com');break;}window.open(u,'_self');})()
内容的提问来源于stack exchange,提问作者user26607610
相关产品推荐
相关产品推荐

