Open In App

Lodash _.replace() Method

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:

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.




// 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.




// 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.

Article Tags :