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 ever need, with examples.

Search & Check

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

// Includes (modern replacement for indexOf !== -1)
str.includes('World');        // true
str.includes('world');         // false (case sensitive)
str.startsWith('Hello');       // true
str.endsWith('JavaScript');    // true

// indexOf / lastIndexOf
str.indexOf('o');              // 4 (first occurrence)
str.lastIndexOf('o');          // 30 (last occurrence)
str.indexOf('xyz');            // -1 (not found)

// Search with regex
str.search(/world/i);          // 7 (case insensitive match position)
Enter fullscreen mode Exit fullscreen mode

Extract Parts

const str = 'JavaScript is awesome';

// Slice (negative = from end)
str.slice(0, 10);             // "JavaScript"
str.slice(-7);                 // "awesome"
str.slice(11);                 // "is awesome"

// Substring (similar but no negative end)
str.substring(0, 10);         // "JavaScript"

// Substr (deprecated but still works)
str.substr(0, 10);            // "JavaScript"

// Split → Array
'one,two,three'.split(',');   // ['one', 'two', 'three']
'  hello world  '.trim().split(/\s+/); // ['hello', 'world']

// Match (regex)
const html = '<div class="test">content</div>';
html.match(/<div[^>]*>/)[0]; // "<div class="test">"
Enter fullscreen mode Exit fullscreen mode

Transform

// Case
'hello'.toUpperCase();         // "HELLO"
'HELLO'.toLowerCase();         // "hello"

// Trim
'  hello  '.trim();           // "hello"
'  hello  '.trimStart();      // "hello  "
'  hello  '.trimEnd();        // "  hello"

// Replace
'hello world'.replace('world', 'universe');
// "hello universe" (first only)

'hello world world'.replace(/world/g, 'universe');
// "hello universe universe" (all)

// Replace with function
'price: 100 USD'.replace(/\d+/, num => `$${Number(num) * 1.1}`);
// "price: 110 USD"

// Repeat
'ha'.repeat(3);                // "hahaha"

// Pad
'5'.padStart(3, '0');         // "005"
'42'.padEnd(6, '=');          // "42===="
Enter fullscreen mode Exit fullscreen mode

Template Literals & Interpolation

const name = 'Alex';
const age = 30;

// Basic interpolation
`My name is ${name} and I'm ${age}`; // "My name is Alex and I'm 30"

// Expressions in templates
`Next year I'll be ${age + 1}`;     // "Next year I'll be 31"
`${name} has ${name.length} letters`; // "Alex has 4 letters"

// Multi-line strings
const email = `
  Hi ${name},

  Your account is ready!

  Best,
  Team
`;

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

highlight`User ${name} scored ${age * 2}`;
// "User <mark>Alex</mark> scored <mark>60</mark>"
Enter fullscreen mode Exit fullscreen mode

Unicode & Encoding

// Character code
'A'.charCodeAt(0);            // 65
String.fromCharCode(65);       // "A"

// Emoji & Unicode
'😀'.length;                   // 2 (surrogate pair!)
[...'😀'].length;              // 1 (spread into array)
'😀'.codePointAt(0);           // 128512

// Normalize (Unicode equivalence)
'é'.normalize('NFC').length;   // 1 (composed)
'é'.normalize('NFD').length;   // 2 (decomposed: e + accent)

// URL encoding
encodeURIComponent('hello world'); // "hello%20world"
decodeURIComponent('hello%20world'); // "hello world"

// Base64
btoa('Hello World');           // "SGVsbG8gV29ybGQ="
atob('SGVsbG8gV29ybGQ=');     // "Hello World"
Enter fullscreen mode Exit fullscreen mode

Practical Recipes

// Slugify: "Hello World!" → "hello-world"
function slugify(str) {
  return str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

// Truncate: "Very long text..." with ellipsis
function truncate(str, maxLen = 100) {
  if (str.length <= maxLen) return str;
  return str.slice(0, maxLen - 3).trim() + '...';
}

// Camel case: "hello-world" → "helloWorld"
function toCamelCase(str) {
  return str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
}

// Kebab case: "helloWorld" → "hello-world"
function toKebabCase(str) {
  return str.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
}

// Capitalize first letter
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// Initials: "John Doe" → "JD"
function initials(name) {
  return name
    .split(' ')
    .map(word => word[0])
    .join('')
    .toUpperCase();
}

// Word count
function wordCount(str) {
  return str.trim().split(/\s+/).filter(Boolean).length;
}

// Reverse string
function reverse(str) {
  return [...str].reverse().join('');
}
Enter fullscreen mode Exit fullscreen mode

What's your go-to string manipulation trick?

Follow @armorbreak for more JavaScript content.

Top comments (0)