Saturday, October 5, 2024
Google search engine
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

Recent Comments