JavaScript - string methods
1. toUpperCase()
and toLowerCase()
These methods change the case of a string.
let text = "Hello World";
console.log(text.toUpperCase()); // "HELLO WORLD"
console.log(text.toLowerCase()); // "hello world"
2. slice()
, substring()
, substr()
These methods extract parts of a string.
-
slice(start, end)
→ extracts fromstart
toend
(not includingend
). Supports negative indices. -
substring(start, end)
→ similar to slice but does not support negative indices. -
substr(start, length)
→ extractslength
characters fromstart
.
let str = "JavaScript";
// slice
console.log(str.slice(0, 4)); // "Java"
console.log(str.slice(-6, -3)); // "Scr"
// substring
console.log(str.substring(0, 4)); // "Java"
console.log(str.substring(3, 7)); // "aScr"
// substr
console.log(str.substr(4, 6)); // "Script"
3. replace()
and replaceAll()
-
replace(searchValue, newValue)
→ replaces the first occurrence. -
replaceAll(searchValue, newValue)
→ replaces all occurrences.
let msg = "I like cats. Cats are cute.";
// replace first occurrence
console.log(msg.replace("Cats", "Dogs")); // "I like cats. Dogs are cute."
// replace all occurrences
console.log(msg.replaceAll("Cats", "Dogs")); // "I like cats. Dogs are cute."
4. split()
and join()
-
split(separator)
→ splits a string into an array. -
join(separator)
→ joins array elements into a string.
let names = "Alice,Bob,Charlie";
let arr = names.split(","); // ["Alice", "Bob", "Charlie"]
let joined = arr.join(" & ");
console.log(joined); // "Alice & Bob & Charlie"
5. includes()
, startsWith()
, endsWith()
-
includes(substring)
→ checks if a string contains a substring. -
startsWith(substring)
→ checks if it starts with a substring. -
endsWith(substring)
→ checks if it ends with a substring.
let phrase = "Hello JavaScript";
console.log(phrase.includes("Java")); // true
console.log(phrase.startsWith("Hello")); // true
console.log(phrase.endsWith("Script")); // true
6. trim()
Removes whitespace from both ends of a string.
let userInput = " hello world ";
console.log(userInput.trim()); // "hello world"