DEV Community

Alex Chen
Alex Chen

Posted on

JavaScript String Methods: The Ultimate Cheat Sheet

JavaScript String Methods: The Ultimate Cheat Sheet

Strings are everywhere. Master these methods and you'll write 50% less string code.

Creating Strings

const s1 = 'single quotes';
const s2 = "double quotes";
const s3 = `template literals`; // Best for most cases!

// Template literal superpowers:
const name = 'Alex';
const age = 30;
`Hello, ${name}! You are ${age} years old.`; // "Hello, Alex! You are 30 years old."

// Multi-line (preserves formatting):
const html = `
  <div class="card">
    <h2>${name}</h2>
    <p>Age: ${age}</p>
  </div>
`;

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

highlight`Hello ${name}, welcome to ${'Dev.to'}!`;
// "Hello <mark>Alex</mark>, welcome to <mark>Dev.to</mark>!"
Enter fullscreen mode Exit fullscreen mode

Searching

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

// Does it contain? (boolean)
str.includes('World');        // true
str.includes('world');        // false (case-sensitive)
str.includes('World', 10);    // false (search from index 10)
str.startsWith('Hello');      // true
str.endsWith('Script.');      // true

// Where is it? (index or -1)
str.indexOf('World');          // 7
str.indexOf('world');         // -1 (not found)
str.lastIndexOf('o');         // 22 (last occurrence)

// Match pattern (returns match object or null)
str.match(/javascript/i);     // ['JavaScript', index: 27]
str.matchAll(/\w+/g);         // Iterator of all word matches

// Search using function (returns first match index or -1)
str.search(/world/i);         // 7
Enter fullscreen mode Exit fullscreen mode

Extracting Parts

const str = 'JavaScript is awesome!';

// Character at position
str.charAt(0);                // 'J'
str[0];                       // 'J' (modern way)
str.charCodeAt(0);            // 74 (Unicode code point)

// Substring
str.slice(0, 10);             // 'JavaScript' (start, end — negative counts from end)
str.slice(-8);                // 'awesome!' (last 8 chars)
str.substring(0, 10);         // 'JavaScript' (like slice but no negatives)
str.substr(0, 10);           // 'JavaScript' (start, length) — DEPRECATED!

// Split into array
'a,b,c,d'.split(',');         // ['a', 'b', 'c', 'd']
'hello world'.split(' ');     // ['hello', 'world']
'2026-05-16'.split('-');      // ['2026', '05', '16']
''.split(',');               // [''] (one empty element)
''.split(/\s+/).filter(Boolean); // [] (truly empty)

// Split with limit
'a,b,c,d,e'.split(',', 3);   // ['a', 'b', 'c'] (only 3 parts)

// Extract by pattern
'abc123def456'.match(/\d+/g); // ['123', '456']
Enter fullscreen mode Exit fullscreen mode

Transforming

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

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

// Replace
'hello world'.replace('world', 'universe'); // 'hello universe'
'aaa-bbb-ccc'.replace(/-/g, ',');         // 'aaa,bbb,ccc' (global replace!)

// Replace with function (powerful!)
'price: $100 tax: $20'.replace(/\$(\d+)/g, (match, amount) => `$${Number(amount) * 1.1}`);
// "price: $110 tax: $22"

// Replace all (modern, no regex needed!)
'aaa bbb aaa ccc'.replaceAll('aaa', 'xxx'); // 'xxx bbb xxx ccc'

// Pad
'5'.padStart(3, '0');       // '005'
'42'.padEnd(5, '.');        // '42...'

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

// Reverse a string
[... 'hello'].reverse().join(''); // 'olleh'
Enter fullscreen mode Exit fullscreen mode

Checking & Validating

const str = 'hello123';

// Length
str.length;                   // 8

// Is it empty?
str.length === 0;            // true/false
''.trim().length === 0;      // whitespace-only check

// Is it all digits?
/^\d+$/.test(str);           // false
/^\d+$/.test('12345');       // true

// Is it valid email?
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test('alex@example.com'); // true

// Is it valid URL?
try { new URL(str); return true; } catch { return false; }

// Count occurrences
(str.match(/l/g) || []).length; // 2 (how many 'l's in 'hello')

// Check if palindrome
const isPalindrome = s => s === [...s].reverse().join('');
isPalindrome('racecar');   // true
isPalindrome('hello');     // false

// Check if contains only ASCII
/^[\x00-\x7F]*$/.test(str);

// Check if contains emoji
/\p{Emoji}/u.test('Hello 🌍'); // true
Enter fullscreen mode Exit fullscreen mode

Converting

// String ↔ Number
parseInt('42px', 10);       // 42
parseFloat('3.14rem');      // 3.14
Number('42');               // 42
+'42';                      // 42
'42' * 1;                   // 42

String(42);                 // '42'
(42).toString();            // '42'
'' + 42;                    // '42'
`${42}`;                    // '42'

// String ↔ Array
Array.from('hello');        // ['h','e','l','l','o']
[...'hello'];               // ['h','e','l','l','o']
['h','e','l','l','o'].join(''); // 'hello'

// String ↔ Object
JSON.parse('{"a":1}');      // {a: 1}
JSON.stringify({a: 1});     // '{"a":1}'
JSON.stringify({a: 1}, null, 2); // Pretty-printed

// Encode/URI
encodeURIComponent('hello world'); // 'hello%20world'
decodeURIComponent('hello%20world'); // 'hello world'
encodeURI('http://example.com?q=hello world');
Enter fullscreen mode Exit fullscreen mode

Practical Utility Functions

// Capitalize first letter
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
capitalize('hello');          // 'Hello'

// Camel case to kebab-case
const camelToKebab = str => str.replace(/[A-Z]/g, '-' + c => c.toLowerCase());
camelToKebab('camelCaseString'); // 'camel-case-string'

// Kebab-case to camelCase
const kebabToCamel = str => str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
kebabToCamel('kebab-case-string'); // 'kebabCaseString'

// Truncate with ellipsis
const truncate = (str, max) => str.length > max ? str.slice(0, max - 3) + '...' : str;
truncate('Hello, World!', 8); // 'Hello...'

// Slugify (URL-friendly)
const slugify = str => str.toLowerCase()
  .trim()
  .replace(/[^\w\s-]/g, '')
  .replace(/[\s_]+/g, '-')
  .replace(/^-+|-+$/g, '');
slugify('Hello, World! How Are You?'); // 'hello-world-how-are-you'

// Initials
const initials = name => name.split(' ').map(w => w[0]).join('').toUpperCase();
initials('Alex Chen');         // 'AC'

// Mask sensitive data
const maskEmail = email => email.replace(/(.{2})(.*)(@.*)/, '$1***$3');
maskEmail('alex@example.com'); // 'al***@example.com'

const maskCard = num => '****-****-****-' + num.slice(-4);
maskCard('4111111111111111');  // '****-****-****-1111'

// Word count
const wordCount = str => str.trim().split(/\s+/).filter(Boolean).length;
wordCount('Hello world, how are you?'); // 5

// Generate random string
const randomStr = (len = 10) => Math.random().toString(36).substring(2, len + 2);
randomStr();                  // e.g., 'x7k2m9pq1n'
Enter fullscreen mode Exit fullscreen mode

Quick Reference

Category Methods
Search includes(), startsWith(), endsWith(), indexOf(), search(), match()
Extract slice(), charAt(), split(), matchAll()
Transform toUpperCase(), toLowerCase(), trim(), replace(), replaceAll(), padStart(), padEnd(), repeat()
Check .length, test with regex
Convert Number(), parseInt(), toString(), JSON.parse/stringify(), encode/decodeURI

What's your go-to string method? Any tricks I missed?

Follow @armorbreak for more JavaScript content.

Top comments (0)