Hiprup

What are modern string methods?

Newer string methods make common text tasks cleaner.

  • includes / startsWith / endsWith — readable substring checks.

  • padStart / padEnd — pad strings to a length (e.g. formatting numbers).

  • trimStart / trimEnd — trim one side.

  • replaceAll — replace every match without a global regex.

  • repeat — repeat a string n times.

Benefit: they replace older regex tricks with clearer, intention-revealing methods.

const str = 'Hello, World!';

// Checking
console.log(str.startsWith('Hello'));  // true
console.log(str.endsWith('!'));        // true
console.log(str.includes('World'));    // true

// Replacing
const csv = 'a,b,c,d';
console.log(csv.replaceAll(',', ' | ')); // 'a | b | c | d'
// replace only replaces first: csv.replace(',', ' | ') = 'a | b,c,d'

// Padding
console.log('5'.padStart(3, '0'));     // '005'
console.log('hi'.padEnd(10, '.'));     // 'hi........'
console.log(String(42).padStart(5));  // '   42'

// Trimming
console.log('  hello  '.trim());       // 'hello'
console.log('  hello  '.trimStart());  // 'hello  '
console.log('  hello  '.trimEnd());    // '  hello'

// Negative indexing
console.log(str.at(-1));               // '!'
console.log(str.at(-2));               // 'd'

// matchAll (returns iterator of all matches)
const text = 'cat 1, dog 2, bird 3';
const matches = [...text.matchAll(/(\w+) (\d)/g)];
matches.forEach(m => console.log(m[1], m[2]));
// 'cat' '1', 'dog' '2', 'bird' '3'

startsWith/endsWith/includes replace indexOf-based checks. replaceAll replaces every occurrence (no /g regex needed). padStart for zero-padding (display formatting). trim/trimStart/trimEnd for whitespace. at(-1) for last character. matchAll returns all regex matches with capture groups.

replaceAll vs replace is the most practical: replace only does the first occurrence. padStart for number formatting ('005'). at(-1) for last character (cleaner than str[str.length-1]). matchAll for regex with capture groups.

What are modern string methods? | Hiprup