Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to detect and replace all the array elements in a string using RegExp in JavaScript?
In JavaScript, you can detect and replace all array elements in a string using regular expressions (RegExp). This technique is useful for text processing, content filtering, and dynamic string manipulation where you need to replace multiple values at once.
Let's explore different methods to detect and replace all array elements in a string using RegExp in JavaScript.
Using RegExp with join() Method
The most efficient approach is to create a single regular expression pattern by joining array elements with the OR operator (|).
Syntax
new RegExp(array.join('|'), 'flags')
Example: Basic Replacement
<!DOCTYPE html>
<html>
<body>
<p id="result1"></p>
<script>
let wordsToReplace = ['duke', 'rx100'];
let text = "rx100 is more better than the duke.";
let regexp = new RegExp(wordsToReplace.join('|'), 'gi');
let result = text.replace(regexp, 'N/A');
document.getElementById("result1").innerHTML = result;
</script>
</body>
</html>
N/A is more better than the N/A.
Using Word Boundaries for Precise Matching
To avoid partial matches, use word boundaries (\b) to ensure only complete words are replaced.
<!DOCTYPE html>
<html>
<body>
<p id="result2"></p>
<script>
let searchArray = ["tp", "best", "way"];
let originalText = "Welcome to tp. The best e-way learning platform.";
let escapedArray = searchArray.map(word =>
word.replace(/[.*+?^${}()|[\]\]/g, '\$&')
);
let pattern = new RegExp('\b(' + escapedArray.join('|') + ')\b', 'gi');
let finalResult = originalText.replace(pattern, 'REPLACED');
document.getElementById("result2").innerHTML = finalResult;
</script>
</body>
</html>
Welcome to REPLACED. The REPLACED e-way learning platform.
Replacing with Different Values
You can replace each array element with different values using a replacement function.
<!DOCTYPE html>
<html>
<body>
<p id="result3"></p>
<script>
let searchTerms = ['John', 'Smith', 'UK', 'JavaScript'];
let replacements = ['Jane', 'Doe', 'USA', 'Python'];
let sentence = "My name is John Smith. I live in UK. I code in JavaScript.";
let replacementMap = {};
searchTerms.forEach((term, index) => {
replacementMap[term.toLowerCase()] = replacements[index];
});
let regex = new RegExp('\b(' + searchTerms.join('|') + ')\b', 'gi');
let result = sentence.replace(regex, (match) => {
return replacementMap[match.toLowerCase()] || match;
});
document.getElementById("result3").innerHTML = result;
</script>
</body>
</html>
My name is Jane Doe. I live in USA. I code in Python.
RegExp Flags Explanation
| Flag | Description | Usage |
|---|---|---|
| g | Global | Replace all occurrences |
| i | Case-insensitive | Ignore case differences |
| m | Multiline | Match across line breaks |
Key Points
- Use
array.join('|')to create OR patterns in RegExp - Add word boundaries
\bfor precise word matching - Escape special characters to avoid RegExp errors
- Use the 'g' flag for global replacement of all matches
- Combine with replacement functions for different replacement values
Conclusion
Using RegExp with array elements provides an efficient way to perform multiple string replacements in a single operation. The key is properly escaping special characters and using appropriate flags for your specific use case.
