Thursday, October 16, 2025
HomeLanguagesJavascriptLodash _.replace() Method

Lodash _.replace() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc.

The _.replace() method replace the matches for pattern in string with replacement. This method is based on String#replace.

Syntax:

_.replace(string, pattern, replacement)

Parameters: This method accepts three parameters as mentioned above and described below:

  • string: This parameter holds the original string.
  • pattern: This parameter holds the pattern string that need to replace.
  • replacement: This parameter holds the replacement string.

Return Value: This method returns the modified string.

Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.

javascript




// Requiring the lodash library 
const _ = require("lodash"); 
  
// Original array 
var 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:

javascript




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


Output:

234 78

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

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS