我需要为 Greasemonkey 编写一个脚本,用于检查 URL,在满足某些条件时替换其中的一部分,然后重新加载页面。
相关 URL 将始终采用以下格式:
https://optionA.example.com/ab/first/second/tonsOfMetadata
https://optionB.example.com/ab/first/second/tonsOfMetadata
我需要脚本来检查“第一/第二”段,然后将其替换为“第三/第四”。这些将永远是相同的。从一个 URL 到另一个 URL 唯一会改变的是元数据和子域(A 或 B)。
这是我正在尝试运行的代码:
var url = window.location.host;
var regex = /^(https?:\/\/)([^.]+\.)(example\.com\/ab\/)first\/second(\/.+)$/i;
if (url.match(regex) != null){
url = window.location.href;
url = url.replace(regex,"$1$2$3third/fourth$4");
return;
}
console.log(url);
window.location.replace(url);
}
我确信我遗漏了一些明显的东西,但我的编码经验有限。我已经从这里改编了代码:Replace parts of a URL in Greasemonkey从这里开始:Rewrite parts of a URL in Greasemonkey and FireFox .
任何帮助将不胜感激,提前致谢!
最佳答案
您可能只需要这个:
var url = window.location.host;
var regex = /^(https?:\/\/)([^.]+\.)(example\.com\/ab\/)first\/second(\/.+)$/i;
if (url.match(regex) != null) {
url = window.location.href;
url = url.replace(regex,"$1$2$3third/fourth$4");
}
console.log(url);
window.location.href = url;
而不是调用替换方法(我认为它不存在)。而且,您的“返回”声明似乎是多余/错误的。
关于javascript - 如何替换 URL 的一段并重新加载页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554352/