AppDividend
Latest Code Tutorials

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

0

Javascript String Replace Example | String.prototype.replace() Tutorial is today’s topic. The replace() method returns the new string with some or all matches of the pattern replaced by the replacement.  The pattern can be the string or the RegExp or Regular Expression, and the replacement can be the string or the function to be called for each match. If the pattern is a string, only the first occurrence will be replaced.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript String Replace Example

The javascript string replace() method does not change the String object it is called on. It only returns a new string if we want to perform a global search and replace, including the g switch in the regular expression. The syntax of Javascript string replace() method is following.

string.replace(searchValue, newValue)

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

// app.js

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

console.log(res);

 

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');
console.log(newstr);

 

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');

console.log(newstr);

 

String.prototype.replace() Tutorial

Switching words in a string

For the replacement text, the script uses the $1 and $2 replacement patterns.

// app.js

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

 

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.

Finally, Javascript String Replace Example | String.prototype.replace() Tutorial is over.

Leave A Reply

Your email address will not be published.

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