Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
String methods are built-in functions that help you work with text. Search, slice, replace, change case - all without changing the original string!
indexOf, includes, startsWith, endsWith
slice, substring, charAt
replace, trim, toUpperCase, toLowerCase
split, join (array method)
Returns the index of first occurrence, or -1 if not found
const text = 'Hello World';
console.log(text.indexOf('World')); // 6
console.log(text.indexOf('xyz')); // -1Returns true if substring exists, false otherwise
const text = 'JavaScript is awesome';
console.log(text.includes('Java')); // true
console.log(text.includes('Python')); // falseCheck if string starts or ends with specific text
const file = 'image.png';
console.log(file.startsWith('image')); // true
console.log(file.endsWith('.png')); // true
console.log(file.endsWith('.jpg')); // falseFinding text in strings
Extract from start to end (supports negative indexes)
const text = 'JavaScript'; console.log(text.slice(0, 4)); // 'Java' console.log(text.slice(4)); // 'Script' console.log(text.slice(-6)); // 'Script' (from end)
Extract between two indexes (no negative indexes)
const text = 'JavaScript'; console.log(text.substring(0, 4)); // 'Java' console.log(text.substring(4)); // 'Script'
Returns character at specific position
const text = 'Hello'; console.log(text.charAt(0)); // 'H' console.log(text.charAt(4)); // 'o' console.log(text[0]); // 'H' (bracket notation works too)
Getting parts of strings
const text = 'hello'; console.log(text.toUpperCase()); // 'HELLO'
const text = 'HELLO'; console.log(text.toLowerCase()); // 'hello'
Changing text case
const text = ' Hello '; console.log(text.trim()); // 'Hello'
const text = ' Hello'; console.log(text.trimStart()); // 'Hello'
const text = 'Hello '; console.log(text.trimEnd()); // 'Hello'
Cleaning up whitespace
Replaces only the first match
const text = 'Hello Hello';
console.log(text.replace('Hello', 'Hi'));
// 'Hi Hello' (only first replaced)Replaces all matches (ES2021)
const text = 'Hello Hello Hello';
console.log(text.replaceAll('Hello', 'Hi'));
// 'Hi Hi Hi' (all replaced)Substituting text
Converts string to array (use array join() to reverse)
const text = 'apple,banana,orange';
// Split by comma
const fruits = text.split(',');
console.log(fruits);
// ['apple', 'banana', 'orange']
// Join back
const joined = fruits.join(', ');
console.log(joined);
// 'apple, banana, orange'Converting strings to arrays
const text = 'Ha'; console.log(text.repeat(3)); // 'HaHaHa'
const num = '5'; console.log(num.padStart(3, '0')); // '005'
const text = 'Hi'; console.log(text.padEnd(5, '!')); // 'Hi!!!'
repeat(), padStart(), padEnd()
const upper = text.toUpperCase()toLowerCase()replace() for all occurrences (use replaceAll())const result = text.toUpperCase()