String Methods and Manipulation
Working with strings and text processing
Challenge
Section titled “Challenge”Parse, transform, and validate strings efficiently. Handle encoding, case conversion, and text search operations.
Explanation
Section titled “Explanation”Strings are sequences of characters. JavaScript provides many built-in methods for manipulation and searching.
Case Conversion
Section titled “Case Conversion”const text = 'Hello World';
text.toUpperCase(); // 'HELLO WORLD'text.toLowerCase(); // 'hello world'
// First letter uppercasefunction capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1);}
// Title casefunction titleCase(str) { return str.split(' ').map(capitalize).join(' ');}Searching and Finding
Section titled “Searching and Finding”const text = 'Hello World JavaScript';
// indexOf: Find position (returns -1 if not found)text.indexOf('World'); // 6text.indexOf('xyz'); // -1
// lastIndexOf: Find last occurrence'banana'.lastIndexOf('a'); // 5
// includes: Check if containstext.includes('World'); // truetext.includes('xyz'); // false
// startsWith and endsWithtext.startsWith('Hello'); // truetext.endsWith('Script'); // true
// search: Find using regextext.search(/world/i); // 6Extraction Methods
Section titled “Extraction Methods”const text = 'Hello World';
// substring vs slice vs substrtext.substring(0, 5); // 'Hello'text.slice(0, 5); // 'Hello'text.slice(-5); // 'World' (negative index)text.substr(0, 5); // 'Hello' (deprecated)
// charAt and charCodeAttext.charAt(0); // 'H'text.charCodeAt(0); // 72String.fromCharCode(72, 101, 108, 108, 111); // 'Hello'
// split: Convert to array'a,b,c'.split(','); // ['a', 'b', 'c']'hello'.split(''); // ['h', 'e', 'l', 'l', 'o']'a b c'.split(' ', 2); // ['a', 'b'] (limit)Replacement and Transformation
Section titled “Replacement and Transformation”const text = 'The cat in the hat';
// replace: First matchtext.replace('at', 'og'); // 'The cog in the hat'
// replaceAll: All matchestext.replaceAll('at', 'og'); // 'The cog in the hog'
// replace with regex'hello world'.replace(/world/, 'universe'); // 'hello universe''hello world'.replace(/\w+/g, w => w.toUpperCase());// 'HELLO WORLD'
// Padding'5'.padStart(3, '0'); // '005''5'.padEnd(3, '0'); // '500'Trimming and Normalization
Section titled “Trimming and Normalization”const text = ' hello world ';
text.trim(); // 'hello world'text.trimStart(); // 'hello world 'text.trimEnd(); // ' hello world'
// repeat'ab'.repeat(3); // 'ababab'
// normalize Unicode'é'.normalize('NFC') === 'é'; // Combine characters'é'.normalize('NFD') === 'é'; // Decompose charactersString Building
Section titled “String Building”// concat: Combine strings'Hello'.concat(' ', 'World'); // 'Hello World'
// Template literals (preferred)const name = 'John';const age = 30;`${name} is ${age} years old`; // 'John is 30 years old'
// Tagged templatefunction highlight(strings, ...values) { return strings.reduce((result, str, i) => { return result + str + (values[i] ? `**${values[i]}**` : ''); }, '');}
highlight`Hello ${name}, you are ${age} years old`;Pattern Matching
Section titled “Pattern Matching”// match: Get all matchesconst text = 'cat bat mat';const matches = text.match(/[cm]at/g);console.log(matches); // ['cat', 'mat']
// matchAll: Iterator (more info)const matches2 = [...text.matchAll(/[cm]at/g)];matches2.forEach(match => { console.log(match[0], match.index); // 'cat' 0, 'mat' 8});
// localeCompare: Compare strings'a'.localeCompare('b'); // -1 (a comes before b)'b'.localeCompare('a'); // 1'a'.localeCompare('a'); // 0Performance Tips
Section titled “Performance Tips”// ❌ Inefficient: Multiple operationslet result = text.replace(/a/g, 'x').replace(/e/g, 'y').replace(/i/g, 'z');
// ✅ Better: Single regexconst mapping = { a: 'x', e: 'y', i: 'z' };const result = text.replace(/[aei]/g, m => mapping[m]);
// String building// ❌ Bad: Repeated concatenationlet str = '';for (let i = 0; i < 1000; i++) { str += 'x';}
// ✅ Good: Array joinconst parts = [];for (let i = 0; i < 1000; i++) { parts.push('x');}const str = parts.join('');