javascript 如何替换url中的哈希

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6950941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:27:47  来源:igfitidea点击:

How to replace hash in url

javascript

提问by poporo

How to replace a url like this

如何替换这样的网址

http://test.com/#part1

to:

到:

http://test.com/part1

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

我知道 location.hash 但它会检测 url 中是否有哈希值。

回答by Joseph Marikle

location.href = location.href.replace(location.hash,location.hash.substr(1))

回答by vol7ron

You can use replace()

您可以使用替换()

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

这是使用的分解版本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');

回答by Santosh Suryavanshi

var file = location.pathname.substring(location.pathname.lastIndexOf("/") + 2);
var location = window.origin + "file";
window.location = location;

回答by PayteR

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

我认为在字符串上使用正则表达式替换最好和最干净的解决方案

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

example

例子

location.href = location.href.replace( /#.*/, "");