Learn Regex Methods in JavaScript

So far, we've only been working with the match() method, but in fact, several other methods are available in JavaScript that allow you to manipulate strings using regular expressions.

String replacing

Besides matching for a pattern, JavaScript also allows you to replace the matched patterns with another string using the replace() method. The method takes two parameters, a regular expression, and a replacement string.

javascript
1let regex = /xyz/;
2let str = "abc xyz abc xyz";
3
4let replacedStr = str.replace(regex, "abc");
5
6console.log(replacedStr);
text
1abc abc abc xyz

Notice that the replace() method returns the processed string, instead of working on the original string directly.

And also, only the first match is replaced by the new string. To find and replace all matches, add a global flag.

javascript
1let regex = /xyz/g;
2let str = "abc xyz abc xyz";
3
4let replacedStr = str.replace(regex, "abc");
5
6console.log(replacedStr);
text
1abc abc abc abc

The second parameter can also be a callback function if you need a more flexible replacement rule. For example, if you want to find all /html/ and /css/ patterns in a text, and then replace them with uppercase letters, this is what you can do:

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉