No dependencies whatsoever. This package declares no dependencies or devDependencies.
Permalink to InstallationInstallation
Permalink to Quick TakeQuick Take
Permalink to ExamplesExamples
- Treat a missing code unit as not being a surrogate
- Inspect the first UTF-16 code unit of an astral character
Purpose
This package tells you whether the first UTF-16 code unit in a string is a high or low surrogate.
JavaScript represents a Unicode character outside the Basic Multilingual Plane as two UTF-16 code units: a high surrogate from U+D800 through U+DBFF, followed by a low surrogate from U+DC00 through U+DFFF. These predicates are useful when scanning that representation one code unit at a time.
API
The two functions share the same input contract:
| Function | Returns true when the first code unit is in |
|---|---|
isHighSurrogate() | |
isHighSurrogate() | U+D800–U+DBFF |
isLowSurrogate() | |
isLowSurrogate() | U+DC00–U+DFFF |
The optional something argument accepts a string or undefined. Omitting it, passing undefined, or passing an empty string returns false:
import {
isHighSurrogate,
isLowSurrogate,
} from "string-character-is-astral-surrogate";
console.log(isHighSurrogate());
// => false
console.log(isLowSurrogate(undefined));
// => false
Both functions inspect only the first UTF-16 code unit. Any remaining code units are ignored. For example, an emoji encoded as a surrogate pair begins with a high surrogate:
const cap = "🧢";
console.log(isHighSurrogate(cap));
// => true
console.log(isLowSurrogate(cap));
// => false
console.log(isLowSurrogate(cap[1]));
// => true
These functions classify individual code units. They do not check whether a high surrogate is followed by a low surrogate, so a lone surrogate also returns true from its corresponding predicate. Validate the pair separately when you need to confirm that a string is well-formed UTF-16.
At runtime, any input other than a string or undefined throws a TypeError. The TypeScript declarations reject those values before runtime.