replace
replace() swaps the first match for new text.
const text = "red apple, red cherry";
console.log(text.replace("red", "green")); // → green apple, red cherry
replaceAll
replaceAll() swaps every match.
const text = "red apple, red cherry";
console.log(text.replaceAll("red", "green")); // → green apple, green cherry
Both return a new string. The original stays the same.
You can pass a regular expression to either method for more powerful matching, see replace() with Regular Expressions. With a regex, replace() needs the g flag to change every match, while replaceAll() insists on it.
Using a function as the replacement
const text = "price: 10 and 20";
const doubled = text.replace(/\d+/g, number => Number(number) * 2);
console.log(doubled); // → price: 20 and 40
split
split() cuts a string into an array, using a separator.
const tags = "html,css,js";
console.log(tags.split(",")); // → ["html", "css", "js"]
const sentence = "one two three";
console.log(sentence.split(" ")); // → ["one", "two", "three"]
console.log("abc".split("")); // → ["a", "b", "c"]
console.log("a-b-c".split("-", 2)); // → ["a", "b"]
join: the opposite
The array method join() turns an array back into a string.
const words = ["JavaScript", "is", "fun"];
console.log(words.join(" ")); // → JavaScript is fun
console.log(words.join("-")); // → JavaScript-is-fun
Together, split and join are a classic way to transform text:
const title = "Learning modern javascript";
const capitalised = title
.split(" ")
.map(word => word[0].toUpperCase() + word.slice(1))
.join(" ");
console.log(capitalised); // → Learning Modern Javascript
The map() call is explained in the Arrays chapter.
Expecting replace to change the string
text.replace("a", "b"); on its own line does nothing useful. Strings are immutable, so save the result: text = text.replace("a", "b").