JavaScript replace: The Complete Guide

Javascript String replace() Tutorial With Example

The replace() function of JavaScript String does not change the String object it is called on.

JavaScript replace

JavaScript string replace() is a built-in method that returns a new string if we want to perform a global search and replace, including the g switch in the regular expression. The pattern can be the string, the RegExp, or Regular Expression, and the replacement can be the string or the function to be called for each match. Only the first occurrence will be replaced if the pattern is a string.


The syntax of the Javascript string replace() method is the following.

string.replace(searchValue, newValue)


The searchValue parameter is required — the value, or regular expression, that will be replaced by the new value. Finally, the newValue parameter is required. It is the value on which we need to replace it with an original string.

// app.js

let str = 'Alibaba is biggest tech company in china';
let res = str.replace('Alibaba', 'Tencent');


Javascript String Replace Example | String.prototype.replace() Tutorial

Defining the regular expression in replace() method

We can also write the regular expression to change that string with a new string.

// app.js

let str = 'Obama is a US president';
let newstr = str.replace(/Obama/i, 'Trump');

Javascript String Replace Example

Using global and ignore with replace()

Global replace can only be done with the regular expression.

// app.js

let re = /bigbangtheory/gi;
let str = 'The bigbangtheory is the best comedy show.';
let newstr = str.replace(re, 'friends');


String.prototype.replace() Tutorial

Switching words in a string

The script uses the $1 and $2 replacement patterns for the replacement text.

// app.js

let re = /(\w+)\s(\w+)/;
let str = 'Krunal Lathiya';
let newstr = str.replace(re, '$2, $1');

Switching words in a string in javascript

If you are replacing the value (and not a regular expression), only the first instance of the value will be replaced.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.