Thursday, October 9, 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
32346 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7095 POSTS0 COMMENTS
Thapelo Manthata
6790 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS