admin管理员组文章数量:1426032
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?
-
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 doneArray.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
1 Answer
Reset to default 11There'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).
本文标签: javascriptStrings that look the same aren39t equalStack Overflow
版权声明:本文标题:javascript - Strings that look the same aren't equal - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745419533a2657840.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论