On this page

Strings and regular expressions

10 min read TextCh. 2 — Data and structures

Template literals

Template literals (backticks) are the modern way to work with strings. They support:

  • Interpolation of expressions with ${}
  • Multiline without the need for \n
  • Tagged templates for custom processing
const price = 99.5;
const message = `The total is: $${price.toFixed(2)}`;
// "The total is: $99.50"

Essential string methods

Strings in JavaScript are immutable: every method returns a new string.

Method Description Example
trim() Removes whitespace at start and end ' hello '.trim() -> 'hello'
includes(s) Checks if it contains the substring 'hello'.includes('ell') -> true
startsWith(s) Checks the beginning 'hello'.startsWith('he') -> true
endsWith(s) Checks the ending 'hello'.endsWith('lo') -> true
slice(i, j) Extracts a portion 'hello'.slice(1, 3) -> 'el'
split(sep) Splits into an array 'a,b'.split(',') -> ['a','b']
replace(a, b) Replaces the first match 'aaa'.replace('a','b') -> 'baa'
replaceAll(a, b) Replaces all matches 'aaa'.replaceAll('a','b') -> 'bbb'

padStart and padEnd

These methods are useful for formatting text to a fixed length:

const id = '7';
console.log(id.padStart(4, '0')); // '0007'
console.log(id.padEnd(4, '-'));   // '7---'

Regular expressions (RegExp)

Regular expressions allow you to search for patterns in text. They are created with literal syntax /pattern/flags or with new RegExp():

Common special characters

Pattern Meaning
\d A digit (0-9)
\w Letter, digit, or underscore
\s Whitespace
. Any character
+ One or more
* Zero or more
? Zero or one
{n,m} Between n and m repetitions
^ Start of the string
$ End of the string

Flags

Flag Description
g Global - finds all matches
i Case insensitive
m Multiline

Useful methods

  • regex.test(str) — Returns true/false if there is a match
  • str.match(regex) — Returns the matches found
  • str.replace(regex, replacement) — Replaces matches

Capture groups

Parentheses () create groups that you can extract individually. Named groups (?<name>...) make the code more readable.


Practice

  1. Format with template literals and padStart: Create a function formatId(id) that receives a number and returns a 6-digit string padded with leading zeros (e.g., 7 -> '000007'). Use template literals to return "ID: 000007".
  2. Split and join strings: Given the string 'apple, banana, cherry, peach', use split to get an array of fruits, map to uppercase each fruit, and join to combine them with ' | '.
  3. Extract data with regex and groups: Write a regular expression with named capture groups to extract the day, month, and year from a date with format 'DD/MM/YYYY'. Test it with '15/03/2026'.

In the next lesson we will learn how to select and modify DOM elements.

Template literals for everything
Use template literals (backticks) whenever you need interpolation or multiline strings. They are more readable than concatenation with +.
Regex in moderation
Regular expressions are powerful but can quickly become unreadable. For complex validations, consider splitting them into multiple simple patterns or using a validation library.
javascript
// Template literals
const name = 'Carlos';
const age = 28;
const bio = `My name is ${name} and I am ${age} years old.
This is a multiline string.`;

// String methods
const text = '  Hello World JavaScript  ';

console.log(text.trim());              // 'Hello World JavaScript'
console.log(text.trim().toLowerCase()); // 'hello world javascript'
console.log(text.trim().toUpperCase()); // 'HELLO WORLD JAVASCRIPT'

console.log(text.includes('World'));    // true
console.log(text.startsWith('  Hello')); // true
console.log(text.endsWith('  '));       // true

// split and join
const csv = 'apple,banana,cherry';
const fruits = csv.split(',');
// ['apple', 'banana', 'cherry']
const joined = fruits.join(' | ');
// 'apple | banana | cherry'

// slice (does not mutate)
const file = 'document.pdf';
const extension = file.slice(file.lastIndexOf('.'));
// '.pdf'

// repeat and padStart
const code = '42';
console.log(code.padStart(6, '0')); // '000042'
console.log('='.repeat(20)); // '===================='

// replaceAll (ES2021)
const path = 'src\\app\\core\\models';
const unix = path.replaceAll('\\', '/');
// 'src/app/core/models'
javascript
// Creating regex
const emailPattern = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
const numberPattern = /^\d+$/;

// test - returns boolean
console.log(emailPattern.test('[email protected]'));  // true
console.log(emailPattern.test('invalid'));         // false

// match - returns matches
const text = 'There are 3 cats and 7 dogs in 2 houses';
const numbers = text.match(/\d+/g);
// ['3', '7', '2']

// replace with regex
const cleaned = '  extra   spaces  '.replace(/\s+/g, ' ').trim();
// 'extra spaces'

// Capture groups
const date = '2026-03-06';
const [, year, month, day] = date.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(`${day}/${month}/${year}`); // '06/03/2026'

// Named groups (ES2018)
const result = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(result.groups.year); // '2026'