Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax:
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Replacing a Substring in a String:
4.2.
JavaScript
4.3.
Using Regular Expressions for Replacement:
4.4.
JavaScript
4.5.
Dynamically Replacing Template Strings:
4.6.
JavaScript
4.7.
Sanitizing User Input:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
How does _.replace() handle patterns not found in the string?
5.2.
Can _.replace() handle complex regular expressions?
5.3.
Is _.replace() suitable for replacing multiple different patterns?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.replace() Method

Author Gaurav Gandhi
0 upvote

Introduction

String manipulation, including replacing parts of a string based on certain patterns or characters, is a common task in programming. Lodash's _.replace() method streamlines this process by allowing you to replace matches of a pattern in a string with a replacement string. 

Lodash _.replace() Method

This function is especially useful in text processing, data sanitization, or user input handling where specific string modifications are required.

Why This Function is Used

The _.replace() function is used to search for a pattern within a string and replace it with a specified replacement string. This is crucial in cases where you need to modify text, such as correcting spelling errors, replacing placeholders with actual data, or removing unwanted characters or phrases from user inputs.

Syntax, Parameter and Return Value

Syntax:

 _.replace([string=''], pattern, replacement)

Parameters:

  • [string=''] (string): The string to modify.
     
  • pattern (RegExp|string): The pattern to replace.
     
  • replacement (string): The string to replace the pattern with.

Return Value: 

(string) - Returns the modified string.

Examples 

Replacing a Substring in a String:

  • JavaScript

JavaScript

var _ = require('lodash');

var text = 'Hello world';

console.log(_.replace(text, 'world', 'there'));
You can also try this code with Online Javascript Compiler
Run Code

Output:

 'Hello there'


Demonstrates replacing a specific substring within a string.

Using Regular Expressions for Replacement:

  • JavaScript

JavaScript

var sentence = 'This is a test. This is only a test.';

var regex = /test/g; // 'g' for global replacement

console.log(_.replace(sentence, regex, 'demo'));
You can also try this code with Online Javascript Compiler
Run Code

Output:

 'This is a demo. This is only a demo.'


Shows using a regular expression to replace all occurrences of a pattern.

Dynamically Replacing Template Strings:

  • JavaScript

JavaScript

var template = 'Name: %name%, Age: %age%';

var data = { name: 'John', age: 30 };

var result = _.replace(template, /%name%/, data.name);

result = _.replace(result, /%age%/, data.age);

console.log(result);
You can also try this code with Online Javascript Compiler
Run Code

Output:

 'Name: John, Age: 30'


An example of using _.replace() for replacing placeholders in a template string.

Sanitizing User Input:

  • JavaScript

JavaScript

var userInput = 'I <3 JavaScript!';

var sanitizedInput = _.replace(userInput, /<3/g, 'love');

console.log(sanitizedInput);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

'I love JavaScript!'


Demonstrates sanitizing user input by replacing specific patterns.

Frequently Asked Questions

How does _.replace() handle patterns not found in the string?

If the pattern is not found in the string, _.replace() returns the original string unchanged.

Can _.replace() handle complex regular expressions?

Yes, _.replace() can handle complex regular expressions, making it versatile for various text manipulation tasks.

Is _.replace() suitable for replacing multiple different patterns?

For multiple different patterns, _.replace() would need to be called multiple times, once for each pattern to replace.

Conclusion

Lodash's _.replace() method is a versatile tool for modifying strings by replacing specified patterns with replacement strings. It's useful for a wide range of text manipulation tasks, from simple string replacements to more complex pattern matching and data sanitization.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass