Javascript 删除window.location.hash中的外来字符和空格
我将帖子标题用于url哈希,如下所示:Javascript 删除window.location.hash中的外来字符和空格,javascript,jquery,hash,window.location,Javascript,Jquery,Hash,Window.location,我将帖子标题用于url哈希,如下所示: window.location.hash = news_title; http://example.com/news.html#This%20Is%20Kul%C3%BCb%C3%BC%20%E2%80%93%20News%20Build 是的,它工作得很好,但像这样: window.location.hash = news_title; http://example.com/news.html#This%20Is%20Kul%C3%BCb%C3%B
window.location.hash = news_title;
http://example.com/news.html#This%20Is%20Kul%C3%BCb%C3%BC%20%E2%80%93%20News%20Build
是的,它工作得很好,但像这样:
window.location.hash = news_title;
http://example.com/news.html#This%20Is%20Kul%C3%BCb%C3%BC%20%E2%80%93%20News%20Build
因为有些标题包含空格和特殊字符
我试过了,但不起作用:
window.location.hash = project_name;
var hash = window.location.hash;
hash = hash.replace('%20', '-');
我该怎么办?谢谢 Replace需要一个全局选项来执行全部替换,您应该首先使用decodeURIComponent(如果有斜杠,则使用decodeURI):
您正在寻找
decodeURIComponent
var hash = decodeURIComponent(window.location.hash)
请参阅urldecode doc谢谢,但如果我使用
decodeURIComponent
,则使用空格获取标题。像这样:这是新闻。但我需要这是新闻。解码后尝试哈希。替换(/\s/g,“-”)-编辑的答案