当网址路径中有哈希时,Javascript url 重定向

Javascript url redirection when there is a hash in url path

本文关键字:Javascript url 重定向 哈希时 路径      更新时间:2023-09-26

我想从这个位置重定向我的网址:

  http://example.com/#!foo

到此位置

http://example.com/folder/#!foo

如果我删除 if 条件,重定向正在工作,但我想重定向我的 url仅当 url 路径中有 # 时。

在过去的 30 分钟内,我一直在尝试以下代码,但没有任何成功。

<script>
if(window.location.hash)
 {
 window.location.assign("http://www.example.com/folder/"+window.location.hash)
 }
</script>

if( window.location.href.indexOf('#') > -1)
 {
 window.location.assign("http://www.example.com/folder/"+window.location.hash)
 }

这应该可以。

var address = window.location.href
if (adderss.indexOf('#') > -1){ window.location.assign("http://www.example.com/folder/"+window.location.hash) }

尝试:

   var url = window.location.href + "";
   var str="";
   if(url.lastIndexOf("#") != -1)
   str = url.substring(url.lastIndexOf("#"),url.length);
   window.location.href = "http://www.example.com/folder/"+str;

希望对您有所帮助,:)干杯!

您可以使用

indexOf来检查字符串中是否存在特定的字符(或字符串)。

<script>
    if (window.location.hash.indexOf('#') >= 0) {
        window.location.assign("http://www.example.com/folder/"+window.location.hash)
    }
</script>

我将尝试以下事件,

window.onhashchange = function(e){ 
  window.location = window.location.pathname+'/foo/'+window.location.hash
}

你为什么不试试 IndexOf

if((window.location.pathname).indexOf('#') > 0)
 {
     window.location.assign("http://www.example.com/folder/"+window.location.hash)
 }