Skip to content

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, substring and at return for negative and for reversed arguments?
  • Why does "a.b".replaceAll(".", "$&$&") return "a..b", and how do $$, $1 and a replacer function change the result?
  • Why does replaceAll throw on a regex without the g flag, and includes on any regex?
  • What does padStart do with a pad string longer than needed, and with an emoji?
  • Which characters does trim remove: 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, substring and at with positive, negative and reversed arguments, one row per call
  • string_methods_replace_js.js — replace and replaceAll with string and regex patterns, the $&, $$ and $1 replacement patterns, a replacer function, and the TypeError for a non-global regex
  • string_methods_pad_trim_split_js.js — padStart, padEnd, trim and split on edge cases (a long pad string, an emoji, a no-break space, a BOM, an empty string), each result through JSON.stringify

See also

Sources to start from