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 inif
block. - Irrespective of the global flag
g
on regex, it will give the same result.
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 returningtrue
as long as it keeps finding the next occurrence of the pattern.
๐ฉ Global Flag Explanation
Did you note the regex /foo/g
? It means:
- Match literally for
foo
. - '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 namedlastIndex
. - It is updated every time you run it.
- When all occurrences are returned, it is set to
0
. -
lastIndex
is usually the lastindex of occurrence + 1
.
Let's revisit the above code with lastIndex
as well.
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.
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.
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:
RegExp.prototype.exec()
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 isnull
.
If you are using a
while
loop like this example, don't forget theg
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.
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.
๐ 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.
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.