【问题标题】:Remove foreign characters and gaps in window.location.hash删除 window.location.hash 中的外来字符和空白
【发布时间】:2018-06-18 20:08:11
【问题描述】:

我正在使用帖子标题作为 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 = project_name;
var hash = window.location.hash;
hash = hash.replace('%20', '-');

我该怎么办?谢谢!

【问题讨论】:

标签: javascript jquery hash window.location


【解决方案1】:

Replace 需要一个全局选项来进行全部替换,你应该首先使用 decodeURIComponent(或者 decodeURI,如果你有斜线):

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

【讨论】:

  • 谢谢,但如果我使用decodeURIComponent,标题会带有空格。像这样:这是新闻。但我需要这就是新闻。
  • 解码后尝试 hash.replace(/\s/g, '-') - 编辑答案
【解决方案2】:

您正在寻找decodeURIComponent

   var hash = decodeURIComponent(window.location.hash)

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

【讨论】:

    猜你喜欢
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2016-05-30
    • 2021-12-26
    相关资源
    最近更新 更多