删除 window.location.hash 中的外来字符和空格

Remove foreign characters and gaps in window.location.hash

我正在为 url 散列使用 post 标题,如下所示:

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):

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

您正在寻找decodeURIComponent

   var hash = decodeURIComponent(window.location.hash)

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