JavaScript logoJavaScriptINTERMEDIATE

JavaScript String Methods

JavaScript string methods cheat sheet covering slice, replace, split, trim, template literals, and text manipulation with examples.

5 min read
javascriptstringsmethodstext

Sign in to mark items as known and track your progress.

Sign in

Case Manipulation

Transform string case for formatting and comparison

Changing Case

Convert strings to uppercase, lowercase, or capitalize for consistent formatting

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

// Locale-specific
'istanbul'.toLocaleUpperCase('tr-TR'); // 'İSTANBUL'

Searching & Testing

Find and test for substrings and patterns within strings

Finding Substrings

Search for text within strings using indexOf, includes, and search methods

javascript
str.indexOf('world');       // 6 (first occurrence)
str.lastIndexOf('o');       // 7 (last occurrence)
str.includes('Hello');      // true
str.startsWith('Hello');    // true
str.endsWith('!');          // false
str.search(/\d+/);          // 5 (regex search)

Accessing Characters

Access individual characters and their codes using charAt, charCodeAt, and bracket notation

javascript
str[0];                    // 'H'
str.charAt(0);             // 'H'
str.charCodeAt(0);         // 72 (Unicode)
str.codePointAt(0);        // 72 (Unicode code point)
String.fromCharCode(72);   // 'H'

Start & End Checking

Check if strings start or end with specific substrings

javascript
// Check string start
const str = 'JavaScript is awesome'
console.log(str.startsWith('Java'))     // true
console.log(str.startsWith('Script', 4)) // true (start from index 4)

// Check string end  
console.log(str.endsWith('awesome'))    // true
console.log(str.endsWith('is', 13))     // true (check up to position 13)
💡 More readable than indexOf() === 0 or slice() checks
⚡ Second parameter specifies search position
📌 Case-sensitive by default - lowercase for case-insensitive
✅ Perfect for validation and conditional logic

Extracting Substrings

Extract portions of strings using various methods

Substring Methods

Extract portions of strings using slice, substring, and substr methods

javascript
str.substring(0, 5);      // 'Hello'
str.substr(6, 5);         // 'World' (deprecated)
str.slice(0, 5);          // 'Hello'
str.slice(-5);            // last 5 chars

// Differences:
// slice: allows negative indices
// substring: swaps args if start > end
// substr: second arg is length (deprecated)

Modern Character Access

Access characters using the modern at() method with negative indexing

javascript
// at() method - supports negative indices
const str = 'Hello World'
console.log(str.at(0))    // 'H' (first character)
console.log(str.at(-1))   // 'd' (last character)
console.log(str.at(-6))   // ' ' (6th from end)
💡 at() is the modern way to access characters
⚡ Negative indices work without length calculation
📌 Returns undefined for out-of-bounds (like bracket notation)
✅ Cleaner than str[str.length - 1] for end access

String Modification

Modify strings through replacement, trimming, and splitting

Replacing Text

Replace text patterns using replace and replaceAll with strings or regex

javascript
str.replace('old', 'new');        // Replace first
str.replace(/old/g, 'new');       // Replace all (regex)
str.replaceAll('old', 'new');     // Replace all (ES2021)

// With function
str.replace(/\d+/g, n => n * 2);  // Transform matches

Trimming & Padding

Remove whitespace with trim methods or add padding to reach desired length

javascript
'  hello  '.trim();       // 'hello'
'  hello  '.trimStart();  // 'hello  '
'  hello  '.trimEnd();    // '  hello'

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

Splitting & Joining

Convert between strings and arrays using split and join methods

javascript
'a,b,c'.split(',');       // ['a', 'b', 'c']
'hello'.split('');        // ['h', 'e', 'l', 'l', 'o']
['a', 'b'].join('-');     // 'a-b'

// With limit
'a,b,c,d'.split(',', 2);  // ['a', 'b']

String Formatting

Format strings with repetition, padding, and localization

Repeat & Concatenation

Repeat strings multiple times or combine them using various methods

javascript
'ab'.repeat(3);           // 'ababab'
'Hello' + ' ' + 'World';  // 'Hello World'
'Hello'.concat(' ', 'World'); // 'Hello World'
`${str1} ${str2}`;         // Template literal

Normalization & Locale

Handle Unicode normalization and locale-specific string operations

javascript
// Unicode normalization
'é'.normalize('NFC');     // Composed form
'é'.normalize('NFD');     // Decomposed form

// Locale comparison
'ä'.localeCompare('z', 'en'); // -1
'ä'.localeCompare('z', 'sv'); // 1 (Swedish)

Template Literals & String.raw

Use template literals for string interpolation and String.raw for raw strings

javascript
// Template literals
const name = 'World'
const greeting = `Hello, ${name}!`  // 'Hello, World!'

// Multiline strings
const html = `
  <div>
    <h1>${name}</h1>
  </div>
`

// String.raw - no escape processing
const path = String.raw`C:\Users\Documents`  // Preserves backslashes
💡 Template literals are the modern way to build strings
⚡ String.raw preserves escape sequences literally
📌 Tagged templates enable DSLs and string processing
✅ Use String.raw for Windows paths and regex patterns

Regular Expressions

Use regex patterns for advanced string operations

Regex String Methods

Use regular expressions with match, matchAll, and search for pattern matching

javascript
str.match(/pattern/g);     // Find all matches
str.search(/pattern/);     // Find index
str.replace(/old/g, 'new'); // Replace matches
str.split(/delimiter/);    // Split by pattern

'test@email.com'.match(/^[^@]+@[^@]+$/); // Email validation