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
false, sometimes we need the
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.
String.prototype.search() is the right way to go in that case.
false. Do not use it in
gon regex, it will give the same result.
true/false based on if a pattern is found or not.
gis used, it can be executed multiple times for the next occurrences. i.e., it will keep returning
trueas long as it keeps finding the next occurrence of the pattern.
Did you note the regex
/foo/g? It means:
In the code, it returns
true twice. The first time, it finds
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
lastIndexis usually the last
index of occurrence + 1.
Let's revisit the above code with
lastIndex as well.
String.prototype.match() gives you the array of all the matches/occurrences of the pattern specified by the regex.
gis not specified in the regex, the results are different. We will be covering later in this article.
String.prototype.match() can also give you the only first matching patterns and starting index of its occurrence.
gis not specified in the regex.
Note that you can also use
RegExp.prototype.exec()for this purpose as well. It is explained in the following heading.
There are two options for you in this case:
Both are explained below:
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.
RegExp.prototype.test(), it is also stateful.
lastIndexevery time you run it.
lastIndexis set to 0 and the result is
If you are using a
whileloop like this example, don't forget the
The results we achieved using
RegExp.prototype.exec() are also achievable using
String.prototype.matchAll(), but in a more convenient manner using
gon your regex.
Iterablewhen you execute this command.
for-ofloop and it takes care of the rest.
.next()according to your use case.
.next() returns an object with
done property returns false until the complete list has been traversed.
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.