最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace hash in url - Stack Overflow

programmeradmin3浏览0评论

How to replace a url like this


to:


I know location.hash but it will detect if there is a hash in url.

How to replace a url like this

http://test./#part1

to:

http://test./part1

I know location.hash but it will detect if there is a hash in url.

Share Improve this question asked Aug 5, 2011 at 3:02 poporopoporo 511 gold badge1 silver badge2 bronze badges 1
  • Possible duplicate of How to remove the hash from window.location (URL) with JavaScript without page refresh? – PayteR Commented Sep 10, 2017 at 12:52
Add a ment  | 

4 Answers 4

Reset to default 7
location.href = location.href.replace(location.hash,location.hash.substr(1))

You can use replace()

Here's a broken down version using windows.location:

var new_url = window.location.protocol + '//'
            + window.location.hostname + '/'
            + window.location.pathname + '/'
            + window.location.hash.replace('#','','g') ;

Or remove all the hashes:

var new_url = (window.location + '').replace('#','','g');
var file = location.pathname.substring(location.pathname.lastIndexOf("/") + 2);
var location = window.origin + "file";
window.location = location;

in my opinion is using regex replace on string best and cleanest solution

.replace( /#.*/, "");

example

location.href = location.href.replace( /#.*/, "");
发布评论

评论列表(0)

  1. 暂无评论