惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Full Disclosure
The Register - Security
The Register - Security
F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
V
Visual Studio Blog
H
Help Net Security
S
Secure Thoughts
U
Unit 42
P
Palo Alto Networks Blog
A
About on SuperTechFans
S
Securelist
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
The Cloudflare Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Scott Helme
Scott Helme
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
P
Proofpoint News Feed
T
Tor Project blog
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 聂微东
C
CERT Recently Published Vulnerability Notes
阮一峰的网络日志
阮一峰的网络日志
P
Privacy International News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
量子位
Security Latest
Security Latest
L
LangChain Blog
The Last Watchdog
The Last Watchdog
Hugging Face - Blog
Hugging Face - Blog
雷峰网
雷峰网
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
有赞技术团队
有赞技术团队
Know Your Adversary
Know Your Adversary
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
W
WeLiveSecurity
Hacker News: Ask HN
Hacker News: Ask HN
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园 - 三生石上(FineUI控件)
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
博客园 - 司徒正美
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Latest news
Latest news
S
Schneier on Security
H
Hacker News: Front Page

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Is it Safe to Compare JavaScript Strings?
Dmitri Pavlutin · 2020-08-18 · via Dmitri Pavlutin Blog

Let's compare 2 strings str1 and str2:


const str1 = 'Hello!';

const str2 = 'Hello!';

str1 === str2; // => true


Because str1 and str2 have the same characters, these strings are equal.

Is it always the case that 2 strings looking the same are equal? Let's try another example:


const str1 = 'café';

const str2 = 'café';

str1 === str2; // => false


While str1 and str2 look the same, the comparison str1 === str2 evaluates to false. How's that possible?

Let's detail into how to correctly compare strings in JavaScript. Before starting, I'm going to familiarize you with the terms of grapheme (a unit of writing) and combining character (specialized character that modify the look of a base character).

1. What's a grapheme

Looking at the following string, what can you say about its content?

You can easily see that it has 4 letters: lowercase c, lowercase a, lowercase f, and lowercase e with acute.

The way a user thinks about a character as a unit of writing is named grapheme. The example string café contains 4 graphemes.

Here's a formal definition of a grapheme:

Grapheme is a minimally distinctive unit of writing in the context of a particular writing system.

Ok, that's all interesting, but how does it relate to the safe comparison of strings? Some graphemes can be rendered using different sequences of characters.

Particularly, there is a special set of characters named combining characters that modify the previous character to create new graphemes. Let's detail combining characters.

2. What's a combining character

Combining character is a character that applies to the precedent base character to create a grapheme.

Combining character include accents, diacritics, Hebrew points, Arabic vowel signs, and Indic matras.

Combining character always require a base character to be applied to. You should avoid displaying them isolated.

For example, é is an atomic grapheme. You can take a lowercase e (the base character) and combine it with combining acute accent ◌́ (the combining character) to render the grapheme: e + ◌́ = é.


const e1 = 'e\u0301';

e1; // renders as "é"


where \u0301 is the unicode escape sequence of the combining character ◌́.

Note, however, that the same é can be represented in a different way using the lowercase e with acute character:


const e2 = 'é';

e2; // renders as "é"


Even though e1 and e2 render the same grapheme, nevertheless, they are different string values:


const e1 = 'e\u0301';

const e2 = 'é';

e1 === e2; // => false


3. Safe comparison of strings

Having a better understanding of graphemes and combining characters, here are a couple of rules for safer strings comparison in JavaScript.

Firstly, you are safe to compare strings that contain characters from Basic Multilangual Plane (including the ASCII characters) using regular comparison operators ===, == or utility function Object.is().


const str1 = 'Hello!';

const str2 = 'Hello!';

str1 === str2; // => true


Both str1 and str2 contain ASCII characters, so you can safely compare them using comparison operators.

Secondly, if you deal with characters above the Basic Multilingual Plane, including combining characters, then you aren't safe to compare strings using ===, == and Object.is(). What you need to do additionally is to normalize the compared strings.


const str1 = 'café';

const str2 = 'cafe\u0301'; // same as 'café'

str1 === str2; // => false

str1.normalize() === str2.normalize(); // => true


In simple words, the string normalization makes canonical-equivalent strings ('café' and 'cafe\u0301' are equivalent because they represent the same graphemes) to have a unique representation (both 'café' and 'cafe\u0301' are normalized to a unique 'café').

4. Summary

You're safe to compare strings directly when their characters are from the Basic Multilingual Plane.

However, if the strings can contain combining characters, then it would be safer to normalize the compared strings to the same form using string.normalize() function. Then perform the comparison on the normalized strings.