close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than whatโ€™s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

๐ŸŽฏ Using Regular Expressions in JavaScript

๐ŸŽฏ Using Regular Expressions in JavaScript
Author
Saqib Ameen
Related tags on daily.dev
toc
Table of contents
arrow-down

๐ŸŽฏ

Regex is hard; we all agree. But it's usage is inevitable at the same time. The core purpose of the regex is matching patterns. We don't need the same info every time we match the patterns.

๐Ÿค” For example, sometimes we only need to know if it exists or not โ€” a true or false, sometimes we need the index, and so on. That's why there exist different methods in JavaScript to use with regex and obtain that particular info.

This article is all about those use cases and the right method to use.

It could be confusing for first-timers. Try to digest what you can, you can always come back to this post when you need it. It's hard to cover all concepts in a single post. Please don't be afraid to ask questions/discuss in the comments section below.

1๏ธโƒฃ Get Only The Index of First Occurrence

String.prototype.search() is the right way to go in that case.

๐Ÿšจ Remember

  • It returns -1 if not found.
  • -1 is not the same as false. Do not use it in if block.
  • Irrespective of the global flag g on regex, it will give the same result.

String.search use example

2๏ธโƒฃ Get A True/False โ€” Exists or Not

RegExp.prototype.test() returns true/false based on if a pattern is found or not.

๐Ÿšจ Remember

  • The return type is bool.
  • The result can be directly used inside if block.
  • When the global flag g is used, it can be executed multiple times for the next occurrences. i.e., it will keep returning true as long as it keeps finding the next occurrence of the pattern.

regexp.test usage example

๐Ÿšฉ Global Flag Explanation

Did you note the regex /foo/g? It means:

  1. Match literally for foo.
  2. 'g' means don't return after the first match. Find all occurrences.

In the code, it returns true twice. The first time, it finds foo in football and the second time in foosball. The third time it returns false and it will keep returning false.

  • RegExp.prototype.test() achieves this by maintaining a property named lastIndex.
  • It is updated every time you run it.
  • When all occurrences are returned, it is set to 0.
  • lastIndex is usually the last index of occurrence + 1.

Let's revisit the above code with lastIndex as well.

Global Flag Explained

2๏ธโƒฃ Get All The Matching Patterns Only

String.prototype.match() gives you the array of all the matches/occurrences of the pattern specified by the regex.

๐Ÿšจ Remember

  • You only get an array in the response when the global flag g is specified.
  • When the global flag g is not specified in the regex, the results are different. We will be covering later in this article.

String.match() usage example

3๏ธโƒฃ Get The Only First Matching Pattern & Starting Index

String.prototype.match() can also give you the only first matching patterns and starting index of its occurrence.

๐Ÿšจ Remember

  • You only get those details when the global flag g is not specified in the regex.
  • An object is returned containing information like the matched pattern, index, and the input string.
  • It can be super helpful in tokenization.

Stirng.match for one occurrence only

Note that you can also use RegExp.prototype.exec() for this purpose as well. It is explained in the following heading.

4๏ธโƒฃ Get All The Matching Patterns & Their Starting Indices

There are two options for you in this case:

  1. RegExp.prototype.exec()
  2. String.prototype.matchAll()

Both are explained below:

RegExp.prototype.exec()

Don't forget to set the global flag g if you intend to use it this way. If omitted, it will behave just like String.prototype.match(), and give the same result and lastIndex (0) every time.

๐Ÿšจ Remember

  • You have to execute it every time in order to obtain details of the next occurrence.
  • Similar to RegExp.prototype.test(), it is also stateful.
  • It updates lastIndex every time you run it.
  • When it's done, lastIndex is set to 0 and the result is null.

RegExp.exec usage example

If you are using a while loop like this example, don't forget the g flag.

String.prototype.matchAll()

The results we achieved using RegExp.prototype.exec() are also achievable using String.prototype.matchAll(), but in a more convenient manner using for-of loop.

๐Ÿšจ Remember

  • It doesn't work without a global flag g on your regex.
  • You get an Iterable when you execute this command.
  • The idea is, you write a simple for-of loop and it takes care of the rest.

String.matchAll usage

If you are familiar with Generators and Iterators in JavaScript, you can also get the iterator and use .next() according to your use case.

.next() returns an object with value and done property. done property returns false until the complete list has been traversed.

String.matchAll as iterator

๐Ÿ™Œ Wrap Up

That's all I have in my mind when I deal with regex in JavaScript โ€” a few use cases and what method to use. It might be helpful next time you do regex in JavaScript.

However, I'd more than interested to know how do you deal with regex in JavaScript? Feel free to share your use cases/approaches in the comments section below.


๐Ÿ‘‹ Follow us on Twitter to stay up-to-date!

Thanks to Daily, developers can focus on code instead of searching for news. Get immediate access to all these posts and much more just by opening a new tab.

Daily Poster

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more