How to Find and Replace Text in JavaScript: A Step-by-Step Guide

Javascript

Find out the proper way to replace occurrences of a String in JavaScript, using regex or other approaches.

Javascript replace

Who commands the game here is the Javascript replace() method. The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. Example:

var str = "Let's eat something!";
var res = str.replace("eat", "code");
console.log(res); // Let's code something!

Replace Occurrences of a String Using Regular Expressions

If you want to replace all occurrences of a String this simple regex /<TERM>/g will do the job:

String.replace(/<TERM>/g, '')

This code above will perform a case sensitive replacement. That means “code” is different from “code”.

Here is an example where I replace all occurrences of the word “code” in the String text.

const text = 'I love code! Code is great'
const newStr = text.replace(/code/g, '')
console.log(newStr); //I love ! Code is great

To perform a case insensitive substitution, i.e., the method will not differentiate ‘code’ from ‘Code’, use the option i in regex: /<TERM>/gi

String.replace(/<TERM>/gi, '')

Example:

const text = 'I love code! Code is great'
const newStr = text.replace(/code/gi, '')
console.log(newStr); //I love !  is great

Replace Occurrences of a String Using split and join

An alternative, although slower than regex, is the use of two JavaScript functions.

The first is split(), which truncates a string when it finds a pattern (case sensitive) and returns an Array with the tokens:

Example:

const text = 'I love code! Code is great'
const newStr = text.split('code')
console.log(newStr); // [ 'I love ', '! Code is great' ]
console.log(newStr[0]); // I love 
console.log(newStr[1]); // ! Code is great

You can then join the parts of the String using the method join().

const finalStr = newStr.join('')
console.log(finalStr) // I love ! Code is great

Or you can just chain it all together:

const text = 'I love code! Code is great'
const newStr = text.split('code').join('')
console.log(newStr) // I love ! Code is great

You can find more examples in the official documentation here.

Check out the other Javascript tutorials, and sign up for our newsletter to receive news!

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Comments