JavaScript String Methods: The Ultimate Cheat Sheet
Strings are everywhere. Master these methods and you'll write cleaner code.
Search & Check
const str = 'Hello, World! Welcome to JavaScript.';
// Includes (ES6+ — use this!)
str.includes('World'); // true
str.includes('world'); // false (case-sensitive)
str.includes('Python'); // false
// Starts with / ends with
str.startsWith('Hello'); // true
str.startsWith('World', 7); // true (from index 7)
str.endsWith('Script.'); // true
str.endsWith('.'); // true
// Index of first/last occurrence
str.indexOf('o'); // 4 (first 'o')
str.indexOf('o', 5); // 8 (first 'o' after index 5)
str.lastIndexOf('o'); // 22 (last 'o')
str.indexOf('xyz'); // -1 (not found)
// Match with regex
str.match(/o/g); // ['o', 'o', 'o'] — all matches
str.match(/javascript/i); // ['JavaScript'] — case insensitive
Extract & Slice
const str = 'JavaScript is awesome';
// charAt — single character
str.charAt(0); // "J"
str[str.length - 1]; // "e" (last character)
// slice — extract portion (negative = from end)
str.slice(0, 10); // "JavaScript"
str.slice(11); // "is awesome"
str.slice(-7); // "awesome"
str.slice(0, -8); // "JavaScript is"
// substring — similar to slice but no negative indices
str.substring(0, 10); // "JavaScript"
// split — string to array
'a,b,c,d'.split(','); // ['a', 'b', 'c', 'd']
'hello world'.split(' '); // ['hello', 'world']
'2026-05-16'.split('-'); // ['2026', '05', '16']
''.split(','); // [''] (empty array with one element)
// match + groups for extraction
const url = 'https://example.com/path?q=1';
url.match(/^https?:\/\/([^\/]+)/)?.[1]; // "example.com"
Transform
// Case conversion
'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 aaa'.replace('a', 'x');
// "xaa bbb aaa" (only first occurrence!)
'aaa bbb aaa'.replaceAll('a', 'x');
// "xxx bbb xxx" (all occurrences!)
// Replace with regex
'hello123world456'.replace(/\d+/g, '-');
// "hello-world-"
// Replace with function
'price: $100, tax: $15'.replace(/\$(\d+)/g, (_, num) => {
return `$${Number(num) * 1.1}`; // Add 10% tax
});
// "price: $110, tax: $16.5"
// Repeat
'ha'.repeat(3); // "hahaha"
'-'.repeat(20); // "--------------------"
// Pad
'5'.padStart(3, '0'); // "005"
'42'.padEnd(5, '.'); // "42..."
'abc'.padStart(10, '-'); // "-------abc"
Convert Types
// String → Number
Number('42'); // 42
parseInt('42px', 10); // 42 (stops at non-digit)
parseFloat('3.14rem'); // 3.14
+'100'; // 100 (unary plus)
'100' * 1; // 100
// Number → String
String(42); // "42"
(42).toString(); // "42"
'' + 42; // "42"
42 + ''; // "42"
// Boolean → String
String(true); // "true"
String(false); // "false"
// Anything → JSON string
JSON.stringify({ a: 1 }); // '{"a": 1}'
JSON.stringify({ a: 1 }, null, 2);
// {
// "a": 1
// }
Template Literals (ES6+)
const name = 'Alex';
const age = 30;
// Basic interpolation
`My name is ${name} and I am ${age} years old.`;
// "My name is Alex and I am 30 years old."
// Expressions in templates
`Next year I'll be ${age + 1}.`;
// "Next year I'll be 31."
// Multi-line strings
const html = `
<div class="card">
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
// Tagged templates (advanced)
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] ? `<mark>${values[i]}</mark>` : '';
return result + str + value;
}, '');
}
highlight`User ${name} has ${age} items`;
// "User <mark>Alex</mark> has <mark>30</mark> items"
Unicode & Internationalization
// Emoji length (surprise! 😱)
'👨👩👧👦'.length; // 11 (not 1!) — it's multiple code points
[...'👨👩👧👦'].length; // 1 (spread into array of graphemes)
// Code points
'A'.codePointAt(0); // 65
String.fromCodePoint(9733); // "★"
// Locale-aware operations
'café'.normalize('NFD'); // Decomposed accents (for accent-insensitive search)
'I'.localeCompare('i'); // 0 (locale-aware comparison)
// Intl APIs
new Intl.NumberFormat('en-US').format(1234567.89);
// "1,234,567.89"
new Intl.NumberFormat('de-DE').format(1234567.89);
// "1.234.567,89"
new Intl.DateTimeFormat('en-US', { dateStyle: 'full' }).format(new Date());
// "Friday, May 16, 2026"
Practical Patterns
Slugify URL
function slugify(text) {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // Remove special chars
.replace(/[\s_]+/g, '-') // Spaces to hyphens
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}
slugify('Hello World! How Are You?');
// "hello-world-how-are-you"
Truncate Text
function truncate(str, maxLength, suffix = '...') {
if (str.length <= maxLength) return str;
return str.slice(0, maxLength - suffix.length) + suffix;
}
truncate('This is a very long sentence that should be truncated.', 20);
// "This is a very lo..."
Title Case
function titleCase(str) {
return str.toLowerCase().replace(
/\b\w/g,
char => char.toUpperCase()
);
}
titleCase('hello WORLD from javascript');
// "Hello World From Javascript"
Camel Case ↔ Snake Case
function snakeToCamel(str) {
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}
snakeToCamel('my_variable_name'); // "myVariableName"
function camelToSnake(str) {
return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
}
camelToSnake('myVariableName'); // "my_variable_name"
Extract Numbers from String
function extractNumbers(str) {
return str.match(/\d+(\.\d+)?/g) || [];
}
extractNumbers('Order #12345: $99.99 shipping');
// ['12345', '99.99']
Quick Reference
| Method | Returns | Example |
|---|---|---|
includes() |
boolean |
'hi'.includes('i') → true |
startsWith() |
boolean |
'hi'.startsWith('h') → true |
endsWith() |
boolean |
'hi'.endsWith('i') → true |
indexOf() |
number or -1 |
'hi'.indexOf('i') → 1 |
slice(start, end) |
string |
'hello'.slice(1,3) → 'el' |
split(sep) |
array |
'a,b'.split(',') → ['a','b'] |
trim() |
string |
' x '.trim() → 'x' |
toUpperCase() |
string |
'hi'.toUpperCase() → 'HI' |
toLowerCase() |
string |
'HI'.toLowerCase() → 'hi' |
replace(old, new) |
string | First occurrence only |
replaceAll(old, new) |
string | All occurrences |
repeat(n) |
string |
'x'.repeat(3) → 'xxx' |
padStart(len, char) |
string |
'5'.padStart(3,'0') → '005' |
match(regex) |
array or null | Regex matches |
charCodeAt(i) |
number | ASCII/Unicode code |
What's your favorite string method trick? Share it below!
Follow @armorbreak for more JavaScript content.
Top comments (0)