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

推荐订阅源

博客园 - 【当耐特】
WordPress大学
WordPress大学
T
The Exploit Database - CXSecurity.com
博客园_首页
MyScale Blog
MyScale Blog
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
F
Full Disclosure
V
V2EX
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News: Ask HN
Hacker News: Ask HN
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Martin Fowler
Martin Fowler
PCI Perspectives
PCI Perspectives
S
Security @ Cisco Blogs
Recorded Future
Recorded Future
Help Net Security
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
Microsoft Azure Blog
Microsoft Azure Blog
K
Kaspersky official blog
G
GRAHAM CLULEY
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
CERT Recently Published Vulnerability Notes
U
Unit 42
T
Tor Project blog
Cloudbric
Cloudbric
Hacker News - Newest:
Hacker News - Newest: "LLM"
MongoDB | Blog
MongoDB | Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Security Latest
Security Latest
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

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 Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries 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
What Actually is a String in JavaScript?
Dmitri Pavlutin · 2020-08-04 · via Dmitri Pavlutin Blog

1. Modeling by visible characters

The simplest way, yet not entirely accurate, to mentally model the JavaScript strings is by a sequence of characters like letters, numbers, and punctuation marks.

The string in the following code sample consists of 5 letters and an exclamation mark:


const message = 'Hello!';


Thinking about strings as a sequence of visible characters also suggests that the number of characters in 'Hello!' string equal to 6:


const message = 'Hello!';

message.length; // => 6


The approach to model the strings by visible characters (glyphs) works well if the characters are from Basic Latin block of characters, also known as the 127 ASCII characters.

But as soon as you deal with more complex characters, for example the emoticons (😀, 😁, 😈), modeling the strings by visible characters becomes inaccurate.

Consider the following string:

You can see that the string contains just one character: the grinning face.

But if you use the smile.length property to determine the number of characters, you might be surprised that it contains 2 units:


const smile = '😀';

smile.length; // => 2


How could that happen: you see one character, while length indicates 2 of them?

It's because JavaScript considers strings as a sequence of code units, rather than a sequence of visible characters.

Let's see in more detail what strings are in JavaScript.

2. Modeling by code units

The specification says what strings are in JavaScript:

The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values (“elements”). The String type is generally used to represent textual data in a running ECMAScript program, in which case each element in the String is treated as a UTF-16 code unit value.

Simply saying, the strings in JavaScript are a sequence of numbers, exactly UTF-16 code unit values.

A code unit is just a number from 0x0000 until 0xFFFF. The magic happens because there is a mapping between the code unit value and a specific character.

For example, the code unit 0x0048 is rendered to the actual character H using the unicode escape sequence \u0048:


const letter = '\u0048';

letter === 'H' // => true


Now let's use UTF-16 code units directly to create the 'Hello!' string:


const message = '\u0048\u0065\u006C\u006C\u006F\u0021';

message === 'Hello!'; // => true

message.length; // => 6


\u0048\u0065\u006C\u006C\u006F\u0021 is how JavaScript sees the strings: as a sequence of code units. Note that the presented sequence has 6 code units, which corresponds to the number of visible characters in the 'Hello!' string.

A Unicode character from Basic Multilangual Plane is encoded with one code unit in UTF-16.

However, characters from non-Basic Multilangual Plane:

require an unseparable pair of code units (named surrogate pair) to be encoded in UTF-16.

For example, the grinning face character '😀', which would have the code unit of 0x1F600 (the number 0x1F600 is bigger than 0xFFFF thus doesn't fit into 16 bits), is encoded with a sequence of 2 code units 0xD83D0xDE00:


const smile = '\uD83D\uDE00';

smile === '😀'; // => true

smile.length; // => 2


The sequence \uD83D\uDE00 is a special pair named surrogate pair.

smile.length evaluates to 2, which denotes that the length property of the string primitive determines the number of code units.

The string iterator is aware of the surrogate pairs. When you invoke the string iterator, for example using the spread operator ..., it counts a surrogate pair as one length unit:


const message = 'Hello!';

const smile = '😀';

[...message].length; // => 6

[...smile].length; // => 1


3. Summary

The simplest way to think about JavaScript string is a sequence of visible characters. This approach works well for English letters, numbers, ASCII characters.

However, saying it strictly, a string in JavaScript is a sequence of UTF-16 code units. string.length property determines the number of code units, rather than the number of visible characters.

Understanding that a string is a sequence of code units is necessary if you work with characters above the Basic Multilingual Plane.

To solidify your knowledge on Unicode, code units, etc, I recommend reading my post What every JavaScript developer should know about Unicode.