String Methods
JavaScript provides numerous built-in methods to manipulate, search, and transform strings effectively.
Basic String Properties and Access
javascriptconst text = 'Hello World'; // Length property console.log(text.length); // 11 // Character access console.log(text[0]); // 'H' console.log(text.charAt(6)); // 'W' console.log(text.charAt(20)); // '' (empty string for out of bounds) // Character codes console.log(text.charCodeAt(0)); // 72 (ASCII code for 'H') console.log(String.fromCharCode(72)); // 'H'
Case Conversion
javascriptconst text = 'Hello World JavaScript'; console.log(text.toLowerCase()); // 'hello world javascript' console.log(text.toUpperCase()); // 'HELLO WORLD JAVASCRIPT' // Capitalize first letter function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); } console.log(capitalize('hello')); // 'Hello' // Title case function toTitleCase(str) { return str.split(' ') .map(word => capitalize(word)) .join(' '); } console.log(toTitleCase('hello world javascript')); // 'Hello World Javascript'
Searching and Finding
javascriptconst text = 'JavaScript is awesome and JavaScript is powerful'; // indexOf - first occurrence console.log(text.indexOf('Script')); // 4 console.log(text.indexOf('Python')); // -1 (not found) console.log(text.indexOf('JavaScript', 10)); // 25 (search from index 10) // lastIndexOf - last occurrence console.log(text.lastIndexOf('JavaScript')); // 25 // includes - check if substring exists console.log(text.includes('awesome')); // true console.log(text.includes('Python')); // false // startsWith and endsWith console.log(text.startsWith('Java')); // true console.log(text.startsWith('Script')); // false console.log(text.endsWith('powerful')); // true console.log(text.endsWith('ful')); // true
Extracting Substrings
javascriptconst text = 'JavaScript Programming'; // slice(start, end) - most flexible console.log(text.slice(0, 10)); // 'JavaScript' console.log(text.slice(11)); // 'Programming' console.log(text.slice(-11)); // 'Programming' (negative = from end) console.log(text.slice(-11, -4)); // 'Program' // substring(start, end) - similar to slice, no negative indices console.log(text.substring(0, 10)); // 'JavaScript' console.log(text.substring(11)); // 'Programming' console.log(text.substring(10, 0)); // 'JavaScript' (swaps if start > end) // substr(start, length) - deprecated but still used console.log(text.substr(11, 7)); // 'Program' console.log(text.substr(-11, 7)); // 'Program'
String Replacement
javascriptconst text = 'Hello World Hello Universe'; // replace - replaces first occurrence console.log(text.replace('Hello', 'Hi')); // 'Hi World Hello Universe' console.log(text.replace('hello', 'Hi')); // 'Hello World Hello Universe' (case sensitive) // replaceAll - replaces all occurrences (ES2021) console.log(text.replaceAll('Hello', 'Hi')); // 'Hi World Hi Universe' // Using regular expressions for global replace console.log(text.replace(/Hello/g, 'Hi')); // 'Hi World Hi Universe' console.log(text.replace(/hello/gi, 'Hi')); // 'Hi World Hi Universe' (case insensitive) // Replace with function const result = text.replace(/Hello/g, (match, offset) => { return `Hi(${offset})`; }); console.log(result); // 'Hi(0) World Hi(12) Universe'
Splitting and Joining
javascript// split - convert string to array const csv = 'apple,banana,orange,grape'; console.log(csv.split(',')); // ['apple', 'banana', 'orange', 'grape'] const sentence = 'Hello world JavaScript'; console.log(sentence.split(' ')); // ['Hello', 'world', 'JavaScript'] console.log(sentence.split('')); // ['H', 'e', 'l', 'l', 'o', ' ', ...] // Limit splits console.log(csv.split(',', 2)); // ['apple', 'banana'] // Split with regex const text = 'apple123banana456orange'; console.log(text.split(/\d+/)); // ['apple', 'banana', 'orange'] // join - convert array to string (Array method, but commonly used with strings) const words = ['Hello', 'world', 'JavaScript']; console.log(words.join(' ')); // 'Hello world JavaScript' console.log(words.join('-')); // 'Hello-world-JavaScript' console.log(words.join('')); // 'HelloworldJavaScript'
Trimming and Padding
javascriptconst text = ' Hello World '; // Trimming whitespace console.log(text.trim()); // 'Hello World' console.log(text.trimStart()); // 'Hello World ' console.log(text.trimEnd()); // ' Hello World' // Padding const num = '5'; console.log(num.padStart(3, '0')); // '005' console.log(num.padEnd(3, '0')); // '500' const time = '9:5'; const [hours, minutes] = time.split(':'); const formattedTime = `${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}`; console.log(formattedTime); // '09:05' // Padding with longer strings console.log('abc'.padStart(10, '123')); // '1231231abc' console.log('abc'.padEnd(10, '123')); // 'abc1231231'
Template Literals
javascriptconst name = 'Alice'; const age = 30; const city = 'New York'; // Basic interpolation const greeting = `Hello, my name is ${name} and I am ${age} years old.`; console.log(greeting); // Multi-line strings const html = ` <div class="user-card"> <h2>${name}</h2> <p>Age: ${age}</p> <p>City: ${city}</p> </div> `; // Expressions in templates const price = 19.99; const tax = 0.08; const total = `Total: $${(price * (1 + tax)).toFixed(2)}`; console.log(total); // 'Total: $21.59' // Conditional content const user = { name: 'Bob', isAdmin: true }; const message = `Welcome ${user.name}${user.isAdmin ? ' (Admin)' : ''}`; console.log(message); // 'Welcome Bob (Admin)' // Function calls in templates function formatCurrency(amount) { return `$${amount.toFixed(2)}`; } const orderTotal = `Order total: ${formatCurrency(123.456)}`; console.log(orderTotal); // 'Order total: $123.46'
Regular Expressions with Strings
javascriptconst text = 'Contact us at john@example.com or call (555) 123-4567'; // search - find position of match console.log(text.search(/\d+/)); // 38 (position of first digit) console.log(text.search(/xyz/)); // -1 (not found) // match - extract matches console.log(text.match(/\w+@\w+\.\w+/)); // ['john@example.com'] console.log(text.match(/\d+/g)); // ['555', '123', '4567'] (global) // matchAll - get all matches with details const emailRegex = /(\w+)@(\w+)\.(\w+)/g; const matches = [...text.matchAll(emailRegex)]; console.log(matches[0]); // Full match details including groups // test with regex (RegExp method) const phoneRegex = /$$\d{3}$$\s\d{3}-\d{4}/; console.log(phoneRegex.test(text)); // true
Practical Examples
javascript// URL slug generation function createSlug(title) { return title .toLowerCase() .trim() .replace(/[^\w\s-]/g, '') // Remove special characters .replace(/[\s_-]+/g, '-') // Replace spaces/underscores with hyphens .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens } console.log(createSlug('Hello World! This is a Test')); // 'hello-world-this-is-a-test' // Email validation function isValidEmail(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email.trim().toLowerCase()); } console.log(isValidEmail('user@example.com')); // true console.log(isValidEmail('invalid-email')); // false // Phone number formatting function formatPhoneNumber(phone) { const cleaned = phone.replace(/\D/g, ''); // Remove non-digits if (cleaned.length === 10) { return cleaned.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3'); } return phone; // Return original if not 10 digits } console.log(formatPhoneNumber('5551234567')); // '(555) 123-4567' console.log(formatPhoneNumber('555-123-4567')); // '(555) 123-4567' // Word count function countWords(text) { return text.trim().split(/\s+/).filter(word => word.length > 0).length; } console.log(countWords('Hello world JavaScript')); // 3 console.log(countWords(' Hello world ')); // 2 // Truncate text function truncate(text, maxLength, suffix = '...') { if (text.length <= maxLength) return text; return text.slice(0, maxLength - suffix.length) + suffix; } console.log(truncate('This is a long text', 10)); // 'This is...' // Extract initials function getInitials(fullName) { return fullName .split(' ') .map(name => name.charAt(0).toUpperCase()) .join(''); } console.log(getInitials('John Doe Smith')); // 'JDS' // Mask sensitive data function maskEmail(email) { const [username, domain] = email.split('@'); const maskedUsername = username.charAt(0) + '*'.repeat(username.length - 2) + username.slice(-1); return `${maskedUsername}@${domain}`; } console.log(maskEmail('john.doe@example.com')); // 'j*****e@example.com' // Parse CSV line function parseCSVLine(line) { const result = []; let current = ''; let inQuotes = false; for (let i = 0; i < line.length; i++) { const char = line[i]; if (char === '"') { inQuotes = !inQuotes; } else if (char === ',' && !inQuotes) { result.push(current.trim()); current = ''; } else { current += char; } } result.push(current.trim()); return result; } console.log(parseCSVLine('John,25,"New York, NY"')); // ['John', '25', 'New York, NY']