Find and fix lone surrogates in strings
Use isWellFormed to diagnose URIError from a split surrogate pair and toWellFormed to repair text before URL encoding.
You trim a search label before putting it in a URL. The label starts with an emoji, and encodeURIComponent throws URIError: URI malformed on the trimmed string. Check the cut first.
A cut can split a character
JavaScript string indexes count UTF-16 code units. The rocket takes two units, a leading surrogate and a trailing surrogate. If you slice off the second unit, the first one can sit in a JavaScript string on its own.
const label = '🚀 launch'
const firstUnit = label.slice(0, 1)
console.log(label.isWellFormed())
console.log(firstUnit.isWellFormed())
try {
encodeURIComponent(firstUnit)
} catch (error) {
console.log(error.name, error.message)
}The intact label prints true, the slice prints false, and encoding the slice prints URIError URI malformed.
The same check catches a trailing surrogate left behind when you cut off the start of a string. isWellFormed() checks that every leading surrogate has a trailing partner and that none of the trailing surrogates stand alone.
Repair text you can afford to change
If you can show a replacement character in the label, use toWellFormed() before encoding. The method returns a string with one U+FFFD for each unpaired surrogate. A complete pair survives the call.
const cut = '🚀 launch'.slice(0, 1)
const repaired = cut.toWellFormed()
console.log(repaired)
console.log(repaired.isWellFormed())
console.log(encodeURIComponent(repaired))
console.log('🚀 launch'.toWellFormed())You see �, true, and %EF%BF%BD for the repaired slice, then the original label for the intact string.
Repair is a policy decision. A placeholder can be fine for a label you display. For an identifier you look up, it changes the key and can collapse two different bad inputs to the same string. Use isWellFormed() to reject a broken identifier before encoding it.
Fix the cut when you own it
If the label arrived intact and your own slice broke it, change the unit you count. For a code-point limit, spread the string into an array before slicing. Each element holds a whole code point, so the single rocket survives.
const label = '🚀 launch'
const firstPoint = [...label].slice(0, 1).join('')
console.log(firstPoint, encodeURIComponent(firstPoint))You get 🚀 %F0%9F%9A%80.
A code point can still be one part of what the reader sees as a character. If you're cutting a label to a visible character limit, count grapheme clusters with Intl.Segmenter.