JavaScript String Methods — Master Text Manipulation

Complete guide to JavaScript string methods: split, join, replace, includes, startsWith, padStart, and template literal tricks.

JavaScript Beginner 📖 7 min

Essential String Methods

const str = 'Hello, World!';

str.toUpperCase();          // 'HELLO, WORLD!'
str.toLowerCase();          // 'hello, world!'
str.trim();                 // Remove whitespace
str.includes('World');      // true
str.startsWith('Hello');    // true
str.endsWith('!');          // true
str.indexOf('World');       // 7
str.slice(0, 5);            // 'Hello'
str.substring(7, 12);       // 'World'

Searching and Replacing

const text = 'Hello World, Hello JavaScript';

text.replace('Hello', 'Hi');                    // First occurrence only
text.replaceAll('Hello', 'Hi');                 // All occurrences
text.split(' ');                                // ['Hello', 'World,', 'Hello', 'JavaScript']
text.match(/\w+/g);                            // All words
text.search(/World/);                           // Index of first match

Padding and Repeating

'5'.padStart(3, '0');     // '005'
'hello'.padEnd(10, '.');   // 'hello.....'
'na'.repeat(3);            // 'nanana'

Practical Examples

// Slugify a string
function slugify(str) {
  return str.toLowerCase().trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-');
}

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

// Truncate with ellipsis
function truncate(str, maxLen) {
  return str.length > maxLen ? str.slice(0, maxLen - 3) + '...' : str;
}

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →