Replace Regular Expression in JavaScript

Understanding Regular Expressions in JavaScript

Regular expressions (regex) are powerful tools for pattern matching and text manipulation. In JavaScript, they are often used with the replace() method to find and replace specific text within strings.

What is a Regular Expression?

A regular expression is a sequence of characters that defines a search pattern. It can be used to check if a string contains the pattern, split a string into parts, or replace parts of a string.

The replace() Method

The replace() method in JavaScript is used to replace parts of a string that match a regular expression. The syntax is as follows:

string.replace(regexp, replacement);
  • regexp: The regular expression to search for.
  • replacement: The string or function that replaces the matched text.

Example 1: Basic Replacement

let str = "Hello World!";
let newStr = str.replace(/World/g, "Universe");
console.log(newStr); // Output: "Hello Universe!"

In this example, World is replaced with Universe. The g flag at the end of the regular expression makes the replacement global, meaning all occurrences will be replaced.

Example 2: Using a Function as Replacement

You can also use a function as the replacement. This function will be called for every match, and its return value will be used as the replacement string.

let str = "The price is $100 and $200";
let newStr = str.replace(/\$(\d+)/g, function(match, p1) {
  return "£" + p1;
});
console.log(newStr); // Output: "The price is £100 and £200"

Special Characters in Regular Expressions

Some characters have special meanings in regular expressions. To use them literally, you need to escape them with a backslash.

  • . matches any character except line terminators.
  • * matches zero or more occurrences of the preceding character.
  • + matches one or more occurrences of the preceding character.
  • ? matches zero or one occurrence of the preceding character.
  • [] defines a character set.
  • () groups characters or expressions.
  • \ escapes special characters.

Example 3: Escaping Special Characters

let str = "This is a test string with dots...";
let newStr = str.replace(/\.\.\./g, "!");
console.log(newStr); // Output: "This is a test string with dots!"

In this example, the ellipsis ... is replaced with !. The dots are escaped because . is a special character in regular expressions.

Common Use Cases

1. Email Validation

function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email);
}

console.log(validateEmail("[email protected]")); // true
console.log(validateEmail("test@example")); // false

2. Phone Number Formatting

let str = "1234567890";
let formattedStr = str.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
console.log(formattedStr); // Output: "(123) 456-7890"

3. Removing HTML Tags

let str = "<p>This is a paragraph.</p>";
let cleanedStr = str.replace(/<[^>]+>/g, "");
console.log(cleanedStr); // Output: "This is a paragraph."

Frequently Asked Questions

Q1: What is the difference between replace() and replace() with a regular expression?

The replace() method can take either a string or a regular expression as its first argument. When a regular expression is used, it allows for more complex pattern matching and replacement capabilities.

Q2: What does the g flag do in a regular expression?

The g flag stands for “global”. It tells the regular expression to find all matches in the string, rather than stopping after the first match.

Q3: How can I replace only the first occurrence of a pattern?

By default, without the g flag, replace() will only replace the first occurrence of the pattern.

Q4: Can I use a function as the replacement in replace()?

Yes, you can. The function will be called for each match, and the returned value will be used as the replacement string.

Q5: How do I escape special characters in a regular expression?

You can escape special characters by placing a backslash \ before them.

Conclusion

Regular expressions are a powerful tool in JavaScript for manipulating strings. The replace() method, combined with regular expressions, allows for flexible and dynamic text replacement. By understanding the syntax and use cases, you can write efficient and effective code for various applications.

Index
Scroll to Top