Skip to the content

Lesson 65 of 296

String methods and regular expressions

What you will learn

  • More string methods for real tasks
  • Splitting and joining
  • What a regular expression is
  • Regex syntax: characters, quantifiers, anchors, groups, flags
  • Using regex with test, match and replace
  • When not to use regex
On this page

Useful string methods (beyond Lesson 32)

MethodExampleResult
at(i)"hello".at(-1)"o"
trimStart() / trimEnd()" hi ".trimEnd()" hi"
padEnd(n, x)"5".padEnd(3, "0")"500"
lastIndexOf(x)"a.b.c".lastIndexOf(".")3
substring(a, b)"hello".substring(1, 4)"ell"
localeCompare(b)"a".localeCompare("b")-1
normalize()Makes accented letters comparable
concat()"a".concat("b")"ab"

slice vs substring: both cut a part. slice accepts negative numbers (counting from the end): "hello".slice(-3) is "llo". Prefer slice.

Common tasks

"hello world".split(" ")                    ["hello", "world"]
"hello".split("")                           ["h", "e", "l", "l", "o"]
"hello".split("").reverse().join("")        "olleh"  (reverse a string)
"Sam".charAt(0).toUpperCase() + "sam".slice(1)    capitalise the first letter
"file.report.pdf".split(".").pop()          "pdf"  (file extension)
"  Sam  ".trim().toLowerCase()              "sam"  (clean user input)

Reversing with split("") breaks some emoji and special characters, because they are made of two code units. [...str].reverse().join("") handles most of them better. This is a good detail to mention in interviews.

What is a regular expression?

A regular expression (regex) is a pattern that describes text. It is used to search, check and replace text by pattern, for example "any 5 digits" or "a word starting with a capital letter".

It is written between slashes:

const pattern = /cat/;
pattern.test("concatenate");      true

Character classes

PatternMatches
.Any single character (except a new line)
\dA digit 0-9
\wA "word" character: letter, digit or underscore
\sWhitespace: space, tab, new line
\D, \W, \SThe opposite of each above
[abc]One of a, b or c
[a-z]Any lowercase letter
[A-Za-z0-9]Any letter or digit
[^0-9]Anything except a digit
\.A real dot (the backslash removes the special meaning)

Quantifiers: how many

PatternMeans
+One or more
*Zero or more
?Zero or one (optional)
{3}Exactly 3
{2,4}Between 2 and 4
{2,}2 or more
/\d+/        one or more digits
/colou?r/    "color" or "colour"
/\d{5}/      exactly five digits

Anchors

PatternMeans
^Start of the text
$End of the text
\bA word boundary

Anchors matter for validation:

/\d{5}/.test("abc12345xyz")       true  (five digits appear somewhere)
/^\d{5}$/.test("abc12345xyz")     false (the whole text must be five digits)
/^\d{5}$/.test("12345")           true

Groups and alternatives

PatternMeans
(abc)A group: treat as one unit, and remember what matched
a|ba or b
(?<name>...)A named group
/^(cat|dog)s?$/.test("dogs")       true

Flags

Written after the closing slash:

FlagMeaning
gGlobal: find all matches, not just the first
iIgnore case
mMultiline: ^ and $ match at each line
/hello/i.test("HELLO")     true

Using regex

test: does it match?

const isPostcodeLike = /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i;
isPostcodeLike.test("LS1 4AP");      true

(That pattern checks the general shape of a UK postcode. Real postcode validation is more complex; for important data, use an official lookup service.)

match: get the matches

"Order 12 and 345".match(/\d+/g)          ["12", "345"]
"Order 12 and 345".match(/\d+/)           ["12", index: 6, ...]  (first match with details)

Named groups:

const m = "2026-11-23".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
m.groups.year       "2026"

replace with regex:

"a-b_c d".replace(/[-_ ]/g, "")             "abcd"
"hello world".replace(/\b\w/g, (c) => c.toUpperCase())     "Hello World"
"07496 261 310".replace(/\s/g, "")          "07496261310"

matchAll: every match with its groups:

for (const m of "a1 b2 c3".matchAll(/([a-z])(\d)/g)) {
  console.log(m[1], m[2]);
}

Testing your regex

Online regex testers show what a pattern matches as you type. Always test with examples that should match and examples that should not.

When not to use regex

  • Email validation: a fully correct email regex is enormous. A simple check plus sending a confirmation email is the practical approach: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ is a reasonable basic check.
  • Parsing HTML: use the DOM or a parser, not regex.
  • Complex logic: if a regex becomes unreadable, split the check into several simple steps.
  • Badly written patterns on long input can take a very long time to run (called "catastrophic backtracking"), which attackers can exploit. Keep patterns simple, especially on user input on the server.

Common mistakes

  • Forgetting ^ and $ in validation patterns.
  • Forgetting to escape . (it means "any character").
  • Forgetting the g flag when replacing every match (or use replaceAll).
  • Reusing a regex with the g flag in test(): it remembers its last position (lastIndex) and gives alternating results.

How to say it in an interview

"For strings I use methods like slice, split, trim, includes and replaceAll, and localeCompare for sorting. Regular expressions describe text patterns with character classes like backslash d, quantifiers like plus and braces, anchors like caret and dollar, groups, and flags like g and i. I use test to validate, match and matchAll to extract, and replace for transformations. For validation I always anchor the pattern. I avoid regex for HTML or very complex rules, and keep server-side patterns simple to avoid catastrophic backtracking."

Key words

WordMeaning
Regular expressionA pattern that describes text
Character classA set of allowed characters, like \d or [a-z]
QuantifierHow many times something repeats, like + or {3}
AnchorA position, like start ^ or end $
GroupPart of a pattern in brackets
FlagAn option after the pattern, like g or i
EscapeUse \ so a special character is treated literally

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.