删除window.location.hash中的外来字符和间隙

时间:2018-01-09 17:59:00

标签: javascript jquery hash window.location

我正在使用url hash的帖子标题,如下所示:

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', '-');

我该怎么办?谢谢!

2 个答案:

答案 0 :(得分:1)

替换需要一个全局选项来替换all,你应该首先使用decodeURIComponent(或者如果你有斜杠,则使用decodeURI):

let hash = decodeURIComponent(window.location.hash).replace(/\s/g, '-');

答案 1 :(得分:0)

您正在寻找decodeURIComponent

   var hash = decodeURIComponent(window.location.hash)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent