JSintroes2021

Modern string methods

Slice, pad, and scan strings without the old workarounds.

A cluster of newer String methods β€” replaceAll, at, padStart/padEnd, trimStart/trimEnd, and matchAll β€” replace regex tricks and substring math with named, readable one-liners that also respect Unicode code points.

replaceAll swaps every occurrence

String.prototype.replace with a plain string changes only the first match β€” to replace all of them you used to need a global regex (/x/g). replaceAll (ES2021) does exactly what its name says with a literal string: "a-b-c".replaceAll("-", "/") gives "a/b/c". It still accepts a regex, but that regex must carry the global flag, otherwise it throws β€” a deliberate guard so the intent is unambiguous.

at indexes from either end

str.at(i) reads a single character by index just like str[i], but it also accepts negative indices that count back from the end. str.at(-1) is the last character β€” no more str[str.length - 1]. It returns undefined when the index is out of range, the same as bracket access.

padStart / padEnd align text

padStart(targetLength, padString) prepends copies of padString until the string reaches targetLength; padEnd appends to the right instead. They're the clean way to zero-pad numbers ("7".padStart(3, "0") β†’ "007") or to align columns in a fixed-width report. If the string is already at least targetLength, it's returned unchanged.

trimStart / trimEnd strip one side

trim removes whitespace from both ends; trimStart and trimEnd remove it from just one. They're handy when leading or trailing space is significant on one side but not the other β€” for example normalising indentation while preserving a trailing newline.

matchAll and code-point iteration

matchAll returns an iterator of every match for a global regex, each entry a full match array with capture groups and an index β€” far cleaner than calling regex.exec in a loop. And because a string is iterable by Unicode code point, spreading it with [...str] or Array.from(str) splits emoji and other astral characters correctly, where str.split("") would tear a surrogate pair in half.

Try it 6 examples

replaceAll changes every match

JSintro
Press Run to execute

replace stops after the first - (a/b-c-d) while replaceAll rewrites them all (a/b/c/d); the final line shows a global regex collapsing each run of whitespace into one _ (1_2_3_4) β€” proof the regex form works when the g flag is present.