JavaScript String Methods: The Ultimate Cheat Sheet
Strings are everywhere. Master these methods and write cleaner code.
Search & Find
const str = 'Hello, World! Welcome to JavaScript.';
// Check existence
str.includes('World'); // true
str.includes('world'); // false (case-sensitive)
str.startsWith('Hello'); // true
str.endsWith('JavaScript.'); // true
// Find position
str.indexOf('World'); // 7
str.indexOf('xyz'); // -1 (not found)
str.lastIndexOf('o'); // 22 (last occurrence)
// Regex search
str.search(/world/i); // 7 (case-insensitive)
str.match(/[A-Z]\w+/g); // ['Hello', 'World', 'Welcome', 'JavaScript']
str.matchAll(/\w+/g); // Iterator of all matches with groups
Extract & Slice
const str = 'Hello, World!';
// Character at position
str[0]; // 'H'
str.charAt(0); // 'H'
str.charCodeAt(0); // 72 (Unicode code point)
str.at(-1); // '!' (negative index works!)
// Substring
str.slice(7, 12); // 'World'
str.slice(-6); // 'orld!'
str.substring(0, 5); // 'Hello'
// Split into array
'hello world'.split(' '); // ['hello', 'world']
'a,b,c,d'.split(','); // ['a', 'b', 'c', 'd']
'abc'.split(''); // ['a', 'b', 'c']
'hello world'.split(/\s+/); // ['hello', 'world']
// Part of string
str.substring(0, 5); // 'Hello'
str.substr(7, 5); // 'World' (start, length) — DEPRECATED, use slice
Transform
// Case
'hello'.toUpperCase(); // 'HELLO'
'HELLO'.toLowerCase(); // 'hello'
'hello world'.toLocaleUpperCase(); // Locale-aware
// Trim whitespace
' hello '.trim(); // 'hello'
' hello '.trimStart(); // 'hello '
' hello '.trimEnd(); // ' hello'
// Pad
'5'.padStart(3, '0'); // '005'
'abc'.padEnd(10, '.'); // 'abc.......'
// Repeat
'ha'.repeat(3); // 'hahaha'
'-'.repeat(20); // '--------------------'
// Replace
'hello world'.replace('world', 'JavaScript'); // 'hello JavaScript'
'aabbcc'.replace(/b/g, 'x'); // 'aaxxcc' (global regex)
'aabbcc'.replaceAll('b', 'x'); // 'aaxxcc' (no regex needed!)
// Normalize Unicode
'café'.normalize('NFC').length; // 4 (composed)
'café'.normalize('NFD').length; // 5 (decomposed: e + accent)
Template Literals — Advanced
const name = 'Alex';
const age = 30;
// Multi-line
const bio = `My name is ${name}
I am ${age} years old
I love JavaScript`;
// Expressions inside ${}
console.log(`${2 + 3}`); // '5'
console.log(`${name.toUpperCase()}`); // 'ALEX'
console.log(`${['a', 'b', 'c'].join(', ')}`); // 'a, b, c'
// 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}, you are ${age}`;
// 'Hello <mark>Alex</mark>, you are <mark>30</mark>'
Practical Patterns
Slug generation
function slugify(text) {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // Remove special chars
.replace(/[\s_]+/g, '-') // Spaces/underscores to hyphens
.replace(/--+/g, '-') // Multiple hyphens to single
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}
slugify('Hello World! This is a Test'); // 'hello-world-this-is-a-test'
slugify(' My Blog Post '); // 'my-blog-post'
Truncate with ellipsis
function truncate(str, maxLength = 100) {
if (str.length <= maxLength) return str;
return str.slice(0, maxLength).replace(/\s+\S*$/, '') + '...';
}
truncate('This is a very long string that needs to be truncated', 20);
// 'This is a very long...'
Capitalize
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
capitalize('hello'); // 'Hello'
const titleCase = (str) => str.replace(
/\b\w/g,
char => char.toUpperCase()
);
titleCase('the quick brown fox'); // 'The Quick Brown Fox'
const camelCase = (str) => str
.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) =>
index === 0 ? word.toLowerCase() : word.toUpperCase()
)
.replace(/[-_\s]+/g, '');
camelCase('hello-world test_case'); // 'helloWorldTestCase'
const kebabCase = (str) => str
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase();
kebabCase('helloWorld TestCase'); // 'hello-world-test-case'
String to various types
// Safe number parsing
const toNumber = (str) => Number(str) || 0;
toNumber('42'); // 42
toNumber('abc'); // 0
toNumber(''); // 0
toNumber(null); // 0
// Parse query string
const params = new URLSearchParams('?page=1&limit=20&sort=name');
params.get('page'); // '1'
params.get('limit'); // '20'
params.has('sort'); // true
params.toString(); // 'page=1&limit=20&sort=name'
// String to boolean
const toBool = (str) => ['true', '1', 'yes'].includes(String(str).toLowerCase());
toBool('true'); // true
toBool('false'); // false
toBool('1'); // true
// Is valid JSON string?
const isJSON = (str) => {
try { JSON.parse(str); return true; }
catch { return false; }
};
Performance Tips
// String concatenation: + is fine for a few, join() for many
// Slow: repeated +
let s = '';
for (let i = 0; i < 10000; i++) s += i; // Creates new string each time!
// Fast: array join
const parts = [];
for (let i = 0; i < 10000; i++) parts.push(i);
parts.join(''); // Much faster
// Or use template literals (modern engines optimize well)
What's your favorite string method?
Follow @armorbreak for more JavaScript content.
Top comments (0)