我想匹配 URL 中的字符串并将我的页面重定向到其他 URL。当前 URL 是:http://example.com/?healing=f29c
这是我的代码:
<script type="text/javascript">
jQuery( document ).ready(function($) {
var redirect_url = 'example.com/healing/';
var current_url = window.location.href;
if (current_url.indexOf('?healing=')){
if(!current_url.match(redirect_url)){
window.location.replace(redirect_url);
}
return false;
}
});
</script>
但我没有得到正确的输出。它开始将其他页面重定向到 URL 中带有或不带有 '?healing=' 字符串的页面。
并且它们的 URL 重复出现http://example.com/product-category/aromafrequencies/example.com/healing/
答案1
你必须做
<script type="text/javascript">
jQuery( document ).ready(function($) {
var redirect_url = 'example.com/healing/';
var current_url = window.location.href;
//please check condition
if (current_url.indexOf('?healing=') > 0){
if(!current_url.match(redirect_url)){
window.location.replace(redirect_url);
}
return false;
}
});
</script>
答案2
function RedirectUrl() {
var expression = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/
var regex = new RegExp(expression);
var current_url = window.location.href;
var redirect_url = "**your redirect page url call here**";
console.log(current_url);
if (current_url.indexOf('/news') > -1) {
where news is the word which is present in the url eg.www.abc.com / news.html
if (!current_url.match(redirect_url) && current_url.match(regex)) {
window.location.replace(redirect_url);
}
}
}
在 jQuery|Javascript 点击事件期间,在需要的地方调用此函数。
RedirectUrl();