Strings & Regex
A string in JavaScript is an immutable primitive: no method changes it in place, they all return a new string. The second key fact — a string is stored in UTF-16, so .length counts code units, not perceived characters, and an emoji "weighs" two. Whoever keeps these two properties in mind never writes bugs about "changing" a string or counting its length.
On top of strings the language gives template literals with interpolation and their advanced form — tagged templates — and, for complex search, regular expressions with flags and two families of methods. Regexes hide a trap of their own — the lastIndex state of the g flag. The full map lives in the layers below.
Topic map
- String basics — the immutability of the primitive and UTF-16 — code units, code points, surrogate pairs.
- String methods —
slice,substring,indexOf,toUpperCase,trim, and their differences. - Searching a string —
includes,startsWith,endsWith,indexOf, and when each fits. - String comparison —
===and<by code units versuslocaleCompare. - Template literals — backticks,
${...}interpolation, and multiline strings. - Tagged templates — the tag function, the array of chunks, the values, and
.raw. - Regex basics — a
/x/literal versusnew RegExp, groups, greediness. - Regex methods —
test/execon the regex versusmatch/matchAll/replace/searchon the string. - Regex flags —
g,i,m,s,u,y, and thelastIndexstate.
Common traps
| Mistake | Consequence |
|---|---|
| Expecting a string method to change it in place | A string is immutable — the method returns a new one, the original stands |
Treating .length as a count of characters | .length counts UTF-16 code units — an emoji gives 2 |
Confusing slice and substring on negative indices | slice counts from the end, substring clamps negatives to 0 |
Comparing strings with </> for human order | Order is by code unit — uppercase before lowercase; you need localeCompare |
Reusing one /g/ regex in a loop | lastIndex accumulates state — some matches are skipped |
Thinking +/* quantifiers are lazy | They are greedy — take the maximum; laziness comes from +?/*? |
Confusing test/exec (on the regex) with match (on the string) | Different receiver and different result type |
Interview relevance
Strings and regexes are asked as a check of attention to detail — whether you understand immutability, encoding, and the state of a g regex. A candidate who answers "how many characters in a string with an emoji" with ".length gives code units, and [...str].length counts by code point" stands out at once.
Typical checks:
- Whether a string is mutable and what happens on
str[0] = 'x'. - What
.lengthcounts and how to iterate a string by code point. - How
slicediffers fromsubstring, andincludesfromindexOf. - Why a shared
/g/regex in a loop skips matches, and whatlastIndexis.
Common wrong answer: "str.replace('a', 'b') changes the string". No — a string is immutable, replace returns a new string, and the original variable does not change without reassignment.