Skip to content
Plurafy

String Methods and Manipulation

Working with strings and text processing

Parse, transform, and validate strings efficiently. Handle encoding, case conversion, and text search operations.

Strings are sequences of characters. JavaScript provides many built-in methods for manipulation and searching.

const text = 'Hello World';
text.toUpperCase(); // 'HELLO WORLD'
text.toLowerCase(); // 'hello world'
// First letter uppercase
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// Title case
function titleCase(str) {
return str.split(' ').map(capitalize).join(' ');
}
const text = 'Hello World JavaScript';
// indexOf: Find position (returns -1 if not found)
text.indexOf('World'); // 6
text.indexOf('xyz'); // -1
// lastIndexOf: Find last occurrence
'banana'.lastIndexOf('a'); // 5
// includes: Check if contains
text.includes('World'); // true
text.includes('xyz'); // false
// startsWith and endsWith
text.startsWith('Hello'); // true
text.endsWith('Script'); // true
// search: Find using regex
text.search(/world/i); // 6
const text = 'Hello World';
// substring vs slice vs substr
text.substring(0, 5); // 'Hello'
text.slice(0, 5); // 'Hello'
text.slice(-5); // 'World' (negative index)
text.substr(0, 5); // 'Hello' (deprecated)
// charAt and charCodeAt
text.charAt(0); // 'H'
text.charCodeAt(0); // 72
String.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)
const text = 'The cat in the hat';
// replace: First match
text.replace('at', 'og'); // 'The cog in the hat'
// replaceAll: All matches
text.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'
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 characters
// 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 template
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? `**${values[i]}**` : '');
}, '');
}
highlight`Hello ${name}, you are ${age} years old`;
// match: Get all matches
const 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'); // 0
// ❌ Inefficient: Multiple operations
let result = text.replace(/a/g, 'x').replace(/e/g, 'y').replace(/i/g, 'z');
// ✅ Better: Single regex
const mapping = { a: 'x', e: 'y', i: 'z' };
const result = text.replace(/[aei]/g, m => mapping[m]);
// String building
// ❌ Bad: Repeated concatenation
let str = '';
for (let i = 0; i < 1000; i++) {
str += 'x';
}
// ✅ Good: Array join
const parts = [];
for (let i = 0; i < 1000; i++) {
parts.push('x');
}
const str = parts.join('');