【问题标题】:Compare strings with different spaces and potentially null characters比较具有不同空格和可能为空字符的字符串
【发布时间】:2017-01-28 11:17:54
【问题描述】:

我目前正在为我正在做的项目制作维基百科刮板。问题是我的代码在尝试比较字符串时有时会产生错误。如果我有看起来相同的字符串,它们有时仍被注册为不同的。例如:

var elementText = $("selector").text();
console.log(elementText); // "abc def"
console.log(elementText === "abc def"); // false

似乎维基百科使用了一些我的代码检测到但不喜欢的奇怪字符。我试过了:

function replaceBadSpaces(string) {
    return decodeURIComponent(encodeURIComponent(string).replace("/%C2%A0/g", "%20"));
}

并使用elementText.replace(/\s+/g, ''),但似乎都不起作用。我怎样才能完全摆脱这些字符,以便直观上相等的字符串实际上是相等的?

注意:我还用== 测试了我的代码,它似乎确实解决了这个问题;但是,为了避免将来出现错误,我想避免使用此修复程序。

【问题讨论】:

  • 你知道你可以download the entire database for free吗?
  • @Liam 我没有。我一定会调查的。也就是说,如果我将来遇到这个问题,我仍然想知道如何解决它。
  • 维基百科使用不间断空格和细空格,几乎没有任何空字符。即使那样,\s 也应该匹配那些。请向我们展示您究竟尝试使用该正则表达式做什么。你绝对不应该使用enocde/decodeURI…
  • 你应该阅读维基百科网站上的Please do not use a web crawler

标签: javascript encoding removing-whitespace


【解决方案1】:

删除replace 的第一个参数周围的引号。这是因为您使用正则表达式(/g)作为替换函数,不需要用引号括起来。

function replaceBadSpaces(string) {
    return decodeURIComponent(encodeURIComponent(string).replace(/%C2%A0/g, "%20"));
}

【讨论】:

  • 只需要使用replace(/\u00a0/g, ' '),不需要使用任何URI编码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
相关资源
最近更新 更多