最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Strings that look the same aren't equal - Stack Overflow

programmeradmin1浏览0评论

Some unit tests are failing. Upon debugging, I traced the problem here

var a = "USD 1,234.12"
var b = "USD 1,234.12"
console.log(a === b)

Some unit tests are failing. Upon debugging, I traced the problem here

var a = "USD 1,234.12"
var b = "USD 1,234.12"
console.log(a === b)

String a has been generated by a currency formatter library and String b has been written by a unit test developer.

I don't understand why these two strings that look the same aren't considered equal by ===. What is happening here?

Share Improve this question edited Apr 11, 2021 at 19:48 ggorlen 58.1k8 gold badges115 silver badges157 bronze badges asked Apr 11, 2021 at 17:01 TSRTSR 20.9k32 gold badges120 silver badges242 bronze badges 8
  • 1 Two strings are only equal if they have the same amount of code units, and, for each index, the code unit of one string matches the code unit of the other string. This level of debugging is missing here. You could have done Array.from(a).findIndex((char, index) => char !== b[index]). You could have done Array.from(a).forEach((char, index) => console.log("a", char, char.codePointAt(), "vs. b", b[index], b[index].codePointAt())), or some other approach. – Sebastian Simon Commented Apr 11, 2021 at 17:14
  • 3 Bad close reason. It's very reproducible (click the run snippet button), it's interesting (if you don't know about different kind of spaces) and has a clear answer. – Evert Commented Apr 11, 2021 at 17:24
  • @Evert this is also half of a debug process, a better question should be "how to do equality tests without considering the different types of spaces in a string" – Mister Jojo Commented Apr 11, 2021 at 17:37
  • @Evert actually, after understanding the problem, how to answer this "how to do equality tests without considering the different types of spaces in a string" – TSR Commented Apr 11, 2021 at 17:39
  • 1 @TSR If that's the scenario, please edit the post to state that. This question has been asked before in various forms, but I don't see an obvious dupe target and this looks like the cleanest reproduction, so I propose it be canonical. Upvoted. – ggorlen Commented Apr 11, 2021 at 19:43
 |  Show 3 more ments

1 Answer 1

Reset to default 11

There's a hidden difference in your two strings. Run this:

var a = "USD 1,234.12"
var b = "USD 1,234.12"

for (var i = 0; i < a.length; i++) {
  console.log(a.codePointAt(i), b.codePointAt(i));
}

The space in the b string is a regular space (32), while the space in the a string is a Unicode non-breaking space (160).

发布评论

评论列表(0)

  1. 暂无评论