Open In App

Lodash _.replace() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.replace() method replaces the matches for pattern in a string with replacement. This method is based on String Replace.

Syntax:

_.replace(string, pattern, replacement);

Parameters:

  • string: This parameter holds the original string.
  • pattern: This parameter holds the pattern string that needs to be replaced.
  • replacement: This parameter holds the replacement string.

Return Value:

This method returns the modified string.

Example 1: In this example, we are replacing a string by the use of the Lodash _.replace() method.

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let string = _.replace('Stay In', 'In', 'Safe');
 
// Using the _.replace() method
let replace_elem = _.replace(string);
 
// Printing the output
console.log(replace_elem);


Output:

Stay Safe

Example 2: In this example, we are replacing a string having numbers by the use of the Lodash _.replace() method.

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Using the _.replace() method
let num = _.replace('234 56 41', '56 41', '78');
 
// Printing the output
console.log(num);


Output:

234 78

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.


Last Updated : 31 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads