DEV Community

Alex Chen
Alex Chen

Posted on

JavaScript String Methods: The Ultimate Cheat Sheet

JavaScript String Methods: The Ultimate Cheat Sheet

Every string method you'll actually use, organized by use case.

Search & Find

const str = 'Hello, World! Welcome to JavaScript.';

// Includes (boolean)
str.includes('World')     // true
str.includes('world')     // false (case-sensitive!)
str.includes('World', 7)  // false (starts searching from index 7)

// Index of first occurrence
str.indexOf('World')      // 7
str.indexOf('world')      // -1 (not found)
str.indexOf('o')          // 4

// Index of last occurrence
str.lastIndexOf('o')      // 31

// startsWith / endsWith
str.startsWith('Hello')   // true
str.startsWith('World')   // false
str.endsWith('.')          // true
str.endsWith('script')     // false

// Search with regex
str.search(/world/i)      // 7 (returns index, -1 if not found)
str.match(/o/g)           // ['o', 'o', 'o'] (all matches)
str.matchAll(/o/g)        // Iterator of match objects

// At specific position
str.charAt(0)             // 'H'
str.at(-1)                // '.' (last character!)
str.charCodeAt(0)         // 72 (UTF-16 code)
str.codePointAt(0)        // 72
Enter fullscreen mode Exit fullscreen mode

Extract & Slice

const str = 'Hello, World!';

// substring(start, end) — negative = 0
str.substring(0, 5)       // 'Hello'
str.substring(7)           // 'World!'
str.substring(-3)          // 'Hello, World!' (negative treated as 0)

// slice(start, end) — supports negative (from end)
str.slice(0, 5)           // 'Hello'
str.slice(-6)             // 'orld!'
str.slice(7, -1)          // 'World'
str.slice(-6, -1)         // 'orld'

// split — string to array
'hello world'.split(' ')           // ['hello', 'world']
'a,b,c,d'.split(',')               // ['a', 'b', 'c', 'd']
'hello'.split('')                  // ['h', 'e', 'l', 'l', 'o']
'a1b2c3'.split(/(\d)/)             // ['a', '1', 'b', '2', 'c', '3']
'hello world  foo'.split(/\s+/)    // ['hello', 'world', 'foo']

// substring by character
str.substring(str.indexOf(','), str.indexOf('!'))
// ', World'
Enter fullscreen mode Exit fullscreen mode

Modify & Transform

// Case
'hello'.toUpperCase()     // 'HELLO'
'HELLO'.toLowerCase()     // 'hello'
'hELLO wORLD'.charAt(0).toUpperCase() + 'hELLO wORLD'.slice(1).toLowerCase()
// 'Hello world' (capitalize first letter)

// Title case
function titleCase(str) {
  return str.replace(/\b\w/g, c => c.toUpperCase());
}
titleCase('hello world from javascript')
// 'Hello World From Javascript'

// Trim whitespace
'  hello  '.trim()        // 'hello'
'  hello  '.trimStart()   // 'hello  '
'  hello  '.trimEnd()     // '  hello'

// Replace
'hello world'.replace('world', 'JavaScript')  // 'hello JavaScript'
'aaa'.replace('a', 'b')                       // 'baa' (first only!)
'aaa'.replaceAll('a', 'b')                    // 'bbb'

// Replace with function
'price: 100, tax: 20'.replace(/\d+/g, (match) => {
  return parseInt(match) * 2;
})  // 'price: 200, tax: 40'

// Replace with regex
'hello 123 world 456'.replace(/\d+/g, 'X')  // 'hello X world X'

// Pad
'5'.padStart(3, '0')       // '005'
'5'.padEnd(3, '0')         // '500'
'hello'.padStart(10, '-')  // '-----hello'
'hello'.padEnd(10, '-')    // 'hello-----'

// Repeat
'ha'.repeat(3)             // 'hahaha'
'-'.repeat(10)             // '----------'
' '.repeat(4)              // '    '
Enter fullscreen mode Exit fullscreen mode

Template Literals & Interpolation

const name = 'Alice';
const age = 30;

// Basic interpolation
`Hello, ${name}!`           // 'Hello, Alice!'
`${name} is ${age} years old` // 'Alice is 30 years old'

// Expressions
`2 + 2 = ${2 + 2}`          // '2 + 2 = 4'
`${name.toUpperCase()}`     // 'ALICE'

// Tagged templates (advanced)
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    const value = values[i] !== undefined ? `**${values[i]}**` : '';
    return result + str + value;
  }, '');
}

highlight`Hello, ${name}! You are ${age} years old.`;
// 'Hello, **Alice**! You are **30** years old.'

// Multi-line
const html = `
  <div class="card">
    <h2>${title}</h2>
    <p>${description}</p>
  </div>
`;
Enter fullscreen mode Exit fullscreen mode

Common Patterns

// 1. Slugify (URL-safe string)
function slugify(str) {
  return str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');
}
slugify('Hello World! This is a Test')
// 'hello-world-this-is-a-test'

// 2. Truncate with ellipsis
function truncate(str, maxLength = 50) {
  if (str.length <= maxLength) return str;
  return str.slice(0, maxLength - 3) + '...';
}
truncate('A very long string that should be truncated')
// 'A very long string that should be truncat...'

// 3. Capitalize words
const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
capitalize('hello')  // 'Hello'

// 4. Remove HTML tags
'<p>Hello <b>world</b></p>'.replace(/<[^>]*>/g, '')
// 'Hello world'

// 5. Count occurrences
function countOccurrences(str, sub) {
  return str.split(sub).length - 1;
}
countOccurrences('hello world hello', 'hello')  // 2
countOccurrences('aaa', 'a')                     // 3

// 6. Reverse string
[...str].reverse().join('')
// or: str.split('').reverse().join('')

// 7. Is palindrome
function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return cleaned === [...cleaned].reverse().join('');
}
isPalindrome('racecar')           // true
isPalindrome('A man, a plan, a canal: Panama')  // true

// 8. Pluralize
function pluralize(count, singular, plural) {
  return count === 1 ? singular : (plural || singular + 's');
}
pluralize(1, 'item')     // 'item'
pluralize(5, 'item')     // 'items'
pluralize(1, 'person', 'people')  // 'person'
pluralize(3, 'person', 'people')  // 'people'

// 9. Generate initials
'Alice Bob Charlie'.split(' ').map(w => w[0]).join('')
// 'ABC'

// 10. Escape HTML (prevent XSS)
function escapeHtml(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
escapeHtml('<script>alert("xss")</script>')
// '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
Enter fullscreen mode Exit fullscreen mode

Quick Reference Card

Method Returns Mutates
includes() boolean No
indexOf() number No
startsWith() boolean No
slice() string No
substring() string No
split() array No
replace() string No
replaceAll() string No
toUpperCase() string No
toLowerCase() string No
trim() string No
padStart() string No
padEnd() string No
repeat() string No
at() string/undefined No
match() array/null No
search() number No

What's your favorite string method trick?

Follow @armorbreak for more JavaScript content.

Top comments (0)