Master JavaScript Replace with Regular Expression Examples

The replace() method in JavaScript is a powerful tool for manipulating strings, and when combined with regular expressions, it becomes even more versatile. Regular expressions allow you to find and manipulate patterns in strings, providing a robust way to handle complex string operations. In this guide, we will explore various examples of using the replace() method with regular expressions in JavaScript.

Understanding Regular Expressions in JavaScript
Understanding Regular Expressions in JavaScript

Before delving into the examples, let's briefly cover the syntax of the replace() method. The basic syntax is as follows: str.replace(regexp|substr, newSubstr). Here, `regexp` or `substr` is the regular expression or substring to be searched, and `newSubstr` is the replacement. If the first argument is a function, it will be used as a callback, allowing for more complex replacements.

a table with two different types of information
a table with two different types of information

Replacing Text with Regular Expressions

The replace() method can use regular expressions to find and replace text in strings. Here are two common use cases:

a computer screen with the word regex on it
a computer screen with the word regex on it

Replacing All Matches

To replace all occurrences of a pattern, you can use the global flag (g) in your regular expression. For instance, let's replace all spaces with hyphens in a string:

JavaScript Statements & Expressions: The Building Blocks of Code 🚀
JavaScript Statements & Expressions: The Building Blocks of Code 🚀

let text = "JavaScript is a fun language";
let result = text.replace(/\s+/g, '-');
console.log(result); // Output: JavaScript-is-a-fun-language

Replacing with a String or Function

You can replace matched text with a static string or a function that returns a string. Let's replace all vowels with an '*' using a function that checks the letter's position:

let text = "Hello, World!";
let result = text.replace(/[aeiou]/gi, (match) => {
  return match === match.toUpperCase() ? '*' : 'x';
});
console.log(result); // Output: H*ll*x, W*rld!

Removing Text with Regular Expressions

JavaScript Recursion Simplified
JavaScript Recursion Simplified

Regular expressions can help remove unnecessary text from strings, such as whitespace, special characters, or duplicate words.

Removing Whitespace

To remove all whitespace from a string, you can match all whitespace patterns with the regular expression:

a diagram with numbers, letters and symbols in different languages on the same page as shown below
a diagram with numbers, letters and symbols in different languages on the same page as shown below

let text = " Remove   whitespace  ";
let result = text.replace(/\s+/g, '');
console.log(result); // Output: Removewhitespacestring

Removing Duplicate Words

Removing duplicate words in a string can be achieved by collapsing a regular expression's match and replacing it with a function:

JavaScript Conditional Operators: Write Smarter Code with ? : 🚀
JavaScript Conditional Operators: Write Smarter Code with ? : 🚀
JavaScript for Loop: The Ultimate Tool for Repeating Tasks 🔄
JavaScript for Loop: The Ultimate Tool for Repeating Tasks 🔄
two different types of font and numbers on the same page, one is for an email
two different types of font and numbers on the same page, one is for an email
How to Become a Hacker
How to Become a Hacker
JavaScript Return Values: Get the Most Out of Your Functions 🚀
JavaScript Return Values: Get the Most Out of Your Functions 🚀
a poster with different types of letters and numbers
a poster with different types of letters and numbers
Remove Line Breaks In Javascript
Remove Line Breaks In Javascript
How to Replace All Occurrences of a String in JavaScript
How to Replace All Occurrences of a String in JavaScript
JavaScript while Loop: Repeat Tasks Efficiently 🔄
JavaScript while Loop: Repeat Tasks Efficiently 🔄
JavaScript Arrow Functions: Write Shorter & Cleaner Code 🚀
JavaScript Arrow Functions: Write Shorter & Cleaner Code 🚀
How to Create a Function in JavaScript: Step-by-Step Guide 🚀
How to Create a Function in JavaScript: Step-by-Step Guide 🚀
JavaScript Increment & Decrement Operators: Simplify Your Code 🔄
JavaScript Increment & Decrement Operators: Simplify Your Code 🔄
Writing Conditional Statements in JavaScript
Writing Conditional Statements in JavaScript
JavaScript Reserved Words: What You Need to Know 🚀
JavaScript Reserved Words: What You Need to Know 🚀
JavaScript Basics You MUST Know
JavaScript Basics You MUST Know
How to use Regular Expression in Java – Tutorial and Importance
How to use Regular Expression in Java – Tutorial and Importance
"Master JavaScript's Slice Method �: Easy Array & String Slicing Tips! 🚀 #CodingTips #WebDev"
"Master JavaScript's Slice Method �: Easy Array & String Slicing Tips! 🚀 #CodingTips #WebDev"
Javascript Loops & Iterations
Javascript Loops & Iterations
The JavaScript Cheat Sheet Every Beginner Wishes They Had
The JavaScript Cheat Sheet Every Beginner Wishes They Had
10 JavaScript Concepts Every Beginner Must Know (Save This Cheat Sheet!)
10 JavaScript Concepts Every Beginner Must Know (Save This Cheat Sheet!)

let text = "I am learning JavaScript, am a developer, am really enjoying it";
let result = text.replace(/\b(\w+)\s+\1\b/g, '$1');
console.log(result); // Output: I am learning JavaScript, a developer, really enjoying it

Regular expressions provide a powerful approach to manipulating strings with JavaScript. Experiment with these examples and combine them to create your own string manipulation solutions. The combination of replace() and regular expressions opens up a world of possibilities for working with text data.

Related Articles

Javascript Symbols Explained Do While Javascript W3schools Html Css Javascript Xml Javascript Replace Text In Html Element Read And Write File In Javascript W3schools What Version Of Javascript Do Browsers Use W3schools Javascript Interval Javascript Set Time With Timezone Replaceall Javascript Example Javascript Replaceall Vs Replace