How to Replace a Whole String using JavaScript

  • 2 min read
  • November 3, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The replace() method operates on a String, returning a new string with the corresponding changes.

Note: JavaScript strings are immutable.

Syntax

The syntax of the replace() method is as follows:

const newStr = str.replace(pattern, newValue)

  • pattern: This is the pattern to replace. It can be either a String or a regular expression.

If the pattern is a String, the replacement will occur only once, for the first match.

  • newValue: This parameter stores the value to replace the pattern with. It can be a String or a function.

When the newValue parameter is a function, it will be invoked for each match.

To replace the whole string, simply pass in the string you wish to replace as an argument for the first parameter (pattern), and the new string as an argument for the second parameter (newValue):

const str = 'Hello my name is Don and I am a web developer';
const str2 = 'I am Rick and you have learned a new trick...';
const replaceAll = str.replace(str, str2);
console.log(replaceAll);
//Expected output: I am Rick and you have learned a new trick...

To learn more about String.replace() check out this link.

 

Related Articles

JavaScript – How to Format Date

JavaScript – How to Use parseInt()

JavaScript – How to Use the toUpperCase() Method

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each