Methods for Replacing Javascript Strings

If you’ve ever wanted to change words in JavaScript, you’re in the right place. Maybe you fixed a typo in user input, or swapped placeholder text with the real deal. Either way, string replacement is something every coder should understand. The best part? It’s way simpler than it sounds.

TL;DR: JavaScript gives you multiple ways to replace text in strings. You can use the replace() method for one change, or a regular expression for multiple. There’s also replaceAll() if you want to swap many of the same thing. Use whichever method fits your goal, and you’ll be golden.

Why Replace Strings in JS?

Before diving into the methods, let’s look at why you’d want to replace strings in the first place:

  • Fixing typos or incorrect values
  • Updating template strings with dynamic values
  • Censoring user input (like hiding bad words)
  • Changing formats (dates, names, etc.)

Meet the replace() Method

This is the go-to way to swap text. It works on any string and is super straightforward.


const greeting = "Hello Bob!";
const newGreeting = greeting.replace("Bob", "Alice");
console.log(newGreeting); // "Hello Alice!"

As you can see, it finds the first match and swaps it out. Easy!

But Watch Out:

replace() only changes the first match it finds. If you have more than one, it won’t touch the rest.


const text = "ha ha ha!";
const updated = text.replace("ha", "ho");
console.log(updated); // "ho ha ha!" (only the first one!)

Want to fix all of them? Read on!

Using replaceAll()

If you’re working with modern JavaScript (ES2021+), then say hello to replaceAll(). This method is your shortcut for replacing every match in one shot.


const text = "ha ha ha!";
const updated = text.replaceAll("ha", "ho");
console.log(updated); // "ho ho ho!"

No regular expressions. No loops. Just tidy code.

Note: replaceAll() doesn’t work in older browsers. If you care about Internet Explorer (ouch), stick with regex below.

Power Tool: Regular Expressions

Want full control? Enter regular expressions (aka /regex/). They let you match patterns instead of plain text.


const messy = "foo123bar123baz";
const clean = messy.replace(/123/g, "-");
console.log(clean); // "foo-bar-baz"

The /123/g is a regex that matches all instances of “123”. The g stands for “global”, meaning “everywhere”. Without it, it would work like replace() and stop after the first one.

Image not found in postmeta

You can also use regex to match more complex things:


const weird = "I have 100 apples and 200 bananas.";
const numbersGone = weird.replace(/\d+/g, "#");
console.log(numbersGone); // "I have # apples and # bananas."

\d+ matches one or more digits. Super useful!

Advanced Trick: Callback Functions

Sometimes, you want the replacement to change based on the match. That’s where a callback function comes in.


const sentence = "Tom has 3 cats, Jerry has 2 cats.";
const updated = sentence.replace(/\d+/g, (match) => {
  return Number(match) + 1; // Add one to each number
});
console.log(updated); // "Tom has 4 cats, Jerry has 3 cats."

This is awesome when you’re working with data that needs to be modified in bulk.

Replacing Using Split and Join

This trick is kind of sneaky but works really well. You break the string at the keyword, then glue it back together with something else.


const message = "hello world world world";
const swap = message.split("world").join("planet");
console.log(swap); // "hello planet planet planet"

Use this when replaceAll() isn’t available. It works everywhere!

Real-World Example: Templating

Ever seen a string with placeholders like {name} or {age}? Let’s write a little template engine using string replacement.


const template = "Hello, {name}! You are {age} years old.";
const data = {
  name: "Sam",
  age: 25
};

const output = template.replace(/{(.*?)}/g, (_, key) => data[key]);
console.log(output); // "Hello, Sam! You are 25 years old."

This uses a regex to find things in braces and swaps them with real values.

Image not found in postmeta

Case Sensitivity Matters

Be careful — replacements are case-sensitive. That means “Apple” and “apple” are different.


const fruit = "Apple banana apple";
console.log(fruit.replace("apple", "orange")); // Only the lowercase one gets changed

To ignore case, use a regular expression with the i flag:


const fixed = fruit.replace(/apple/i, "orange");
console.log(fixed); // "orange banana apple"

Pro Tip: Chaining Replacements

You can chain multiple replace methods together. Just remember that each one returns a new string.


let original = "The red house on red hill";
let changed = original.replace("red", "blue").replace("house", "cabin");
console.log(changed); // "The blue cabin on red hill"

Sometimes you need layers of changes — this is a neat way to do that.

What About Replacing Characters?

You may want to change single characters, like dashes to spaces or slashes to dots. Use replace() or replaceAll() the same way:


const date = "2024-06-23";
const newDate = date.replaceAll("-", "/");
console.log(newDate); // "2024/06/23"

Short. Sweet. Simple.

Bonus: Censoring Bad Words 🚫

Let’s say your app needs to bleep out rude language. You can keep a list and loop through them:


const input = "This is a dumb and silly idea.";
const badWords = ["dumb", "silly"];
let clean = input;

badWords.forEach(word => {
  const regex = new RegExp(word, "gi");
  clean = clean.replace(regex, "*");
});

console.log(clean); // "This is a * and * idea."

This is a great use of dynamic regular expressions.

Final Thoughts

Replacing strings in JavaScript is like baking cookies — lots of methods, all tasty in their own way. Whether it’s a simple replace() or a supercharged regex with callbacks, you’ve now got a great toolkit to call on.

Try them out. Mix and match. Don’t be afraid to experiment.

Image not found in postmeta

Quick Recap:

  • replace() – swaps the first match
  • replaceAll() – replaces all occurrences
  • RegEx + replace() – for patterns and power moves
  • Callback Function – when you want to compute the new value
  • split().join() – old school but effective

Now go out there and become a string-replacing ninja! 🥷