String methods — slice, padStart, at, replaceAll and the rest¶
Level: 101 · for anyone who has written a line of JavaScript
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: "hello".slice(-3) is "llo" but substring(-3) is the whole string, because substring treats negatives as 0 and swaps reversed ends; and a replacement string still has special patterns: "a.b".replaceAll(".", "$&$&") is "a..b", since $& means the matched text.
Keywords: slice, substring, padStart, at, replaceAll, split
What the finished page will answer¶
- What do
slice,substringandatreturn for negative and for reversed arguments? - Why does
"a.b".replaceAll(".", "$&$&")return"a..b", and how do$$,$1and a replacer function change the result? - Why does
replaceAllthrow on a regex without thegflag, andincludeson any regex? - What does
padStartdo with a pad string longer than needed, and with an emoji? - Which characters does
trimremove: a no-break space, a BOM, an ideographic space? - What do
"".split(",")and"".split("")return?
Examples it will need¶
-
string_methods_slicing_js.js—slice,substringandatwith positive, negative and reversed arguments, one row per call -
string_methods_replace_js.js—replaceandreplaceAllwith string and regex patterns, the$&,$$and$1replacement patterns, a replacer function, and theTypeErrorfor a non-global regex -
string_methods_pad_trim_split_js.js—padStart,padEnd,trimandspliton edge cases (a long pad string, an emoji, a no-break space, a BOM, an empty string), each result throughJSON.stringify
See also¶
- Strings are UTF-16 — why every index these methods take is a code-unit index
- Named groups and replacements —
$<name>, the other replacement patterns and replacer functions RegExp.escape— matching user text literally when the pattern must be a regex- Arrays —
atand negative indexes behave the same on arrays - Primitives and wrappers — strings are immutable, so every method returns a new one
- Python:
stripis a set, not a prefix ↗ — in Python,striptakes a set of characters, not a prefix - Java text: Reverse and substring cut characters in half ↗ — in Java,
substringcuts surrogate pairs the same way - Python: Slicing is not indexing ↗ — in Python, slices forgive bad bounds where indexes do not