Skip to content

JavaScript Tutorial Strings

JavaScript replace(), replaceAll() and split()

Lesson 34 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

replace

replace() swaps the first match for new text.

script.js
JS
const text = "red apple, red cherry";

console.log(text.replace("red", "green")); // → green apple, red cherry

replaceAll

replaceAll() swaps every match.

script.js
JS
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

script.js
JS
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.

script.js
JS
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.

script.js
JS
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:

script.js
JS
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.

warning
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").