<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/blog/using-regular-expressions-in-javascript/" -->

---
title: 🎯 Using Regular Expressions in JavaScript | daily.dev
description: Learn the use of regular expressions and regex in JavaScript. Explore practical developer news, tutorials, and tools read by millions of developers worldwide.
canonical: https://daily.dev/blog/using-regular-expressions-in-javascript/
og:type: article
og:url: https://daily.dev/blog/using-regular-expressions-in-javascript/
og:title: 🎯 Using Regular Expressions in JavaScript | daily.dev
og:description: Learn the use of regular expressions and regex in JavaScript. Explore practical developer news, tutorials, and tools read by millions of developers worldwide.
og:image: https://media.daily.dev/image/upload/s--Clr2VYHk--/f_auto,q_auto/v1/recruiter-landing/5ef3ba37b75de71b0399c805_8gbjyb9iyrmsghn9aqrp_5e7c86e47e?_a=BAMAMiB80
og:site_name: daily.dev
og:locale: en_US
article:published_time: 2020-04-02
article:modified_time: 2026-05-15T14:26:37.480Z
article:author: Saqib Ameen
twitter:card: summary_large_image
twitter:site: @dailydotdev
twitter:creator: @dailydotdev
twitter:title: 🎯 Using Regular Expressions in JavaScript | daily.dev
twitter:description: Learn the use of regular expressions and regex in JavaScript. Explore practical developer news, tutorials, and tools read by millions of developers worldwide.
twitter:image: https://media.daily.dev/image/upload/s--Clr2VYHk--/f_auto,q_auto/v1/recruiter-landing/5ef3ba37b75de71b0399c805_8gbjyb9iyrmsghn9aqrp_5e7c86e47e?_a=BAMAMiB80
---

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.

## [](#get-only-the-index-of-first-occurrence)1️⃣ Get Only The Index of First Occurrence

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

### [](#remember)🚨 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](https://res.cloudinary.com/practicaldev/image/fetch/s--rXAqQ-w9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c5hwcnud74s9882bjgij.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--rXAqQ-w9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c5hwcnud74s9882bjgij.png)

## [](#get-a-raw-truefalse-endraw-exists-or-not)2️⃣ Get A `True/False` — Exists or Not

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

### [](#remember)🚨 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](https://res.cloudinary.com/practicaldev/image/fetch/s--NpG6p4Hr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/tjjif7iv0zk4vf9l7ucx.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--NpG6p4Hr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/tjjif7iv0zk4vf9l7ucx.png)

### [](#global-flag-explanation)🚩 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](https://res.cloudinary.com/practicaldev/image/fetch/s--Y_Um4wh6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/49nmodfkq7ug4ha7f8bz.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--Y_Um4wh6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/49nmodfkq7ug4ha7f8bz.png)

## [](#get-all-the-matching-patterns-only)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)🚨 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](https://res.cloudinary.com/practicaldev/image/fetch/s--tdQ29S59--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/vxgdlnv9uz59r6jco273.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--tdQ29S59--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/vxgdlnv9uz59r6jco273.png)

## [](#get-the-only-first-matching-pattern-amp-starting-index)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)🚨 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](https://res.cloudinary.com/practicaldev/image/fetch/s--3rSiGMob--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/f04sgc2er5pbmilqds54.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--3rSiGMob--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/f04sgc2er5pbmilqds54.png)

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

## [](#get-all-the-matching-patterns-amp-their-starting-indices)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:

## [](#-raw-regexpprototypeexec-endraw-)`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)🚨 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](https://res.cloudinary.com/practicaldev/image/fetch/s--F_4E3Emq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/y5610d4f2b8vr5qt9nwd.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--F_4E3Emq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/y5610d4f2b8vr5qt9nwd.png)

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

## [](#-raw-stringprototypematchall-endraw-)`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)🚨 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](https://res.cloudinary.com/practicaldev/image/fetch/s--YYsIntZ---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/vtzyrexjtykjaaiu9542.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--YYsIntZ---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/vtzyrexjtykjaaiu9542.png)

> 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](https://res.cloudinary.com/practicaldev/image/fetch/s--DJ4kgK72--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/0jr5xgsu6f4mm1b6nd0o.png)](https://res.cloudinary.com/practicaldev/image/fetch/s--DJ4kgK72--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/0jr5xgsu6f4mm1b6nd0o.png)

## [](#wrap-up)🙌 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](https://r.daily.dev/twitter) to stay up-to-date!

_[Thanks to Daily](https://r.daily.dev/web), 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](https://res.cloudinary.com/practicaldev/image/fetch/s--dBpfnoTv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/od2407i0eogvtdm0ddhk.jpeg)](https://r.daily.dev/web)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/og-image.png?v=a830cdf1","width":1200,"height":630},"sameAs":["https://twitter.com/dailydotdev","https://www.linkedin.com/company/dailydotdev","https://github.com/dailydotdev","https://www.instagram.com/dailydotdev"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","description":"Free, personalized developer news aggregator. Stay on top of software development news, AI coding tools, and web dev - curated daily from trusted sources.","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}},{"@type":"WebPage","@id":"https://daily.dev/blog/using-regular-expressions-in-javascript/","url":"https://daily.dev/blog/using-regular-expressions-in-javascript/","name":"🎯 Using Regular Expressions in JavaScript | daily.dev","description":"Learn the use of regular expressions and regex in JavaScript. Explore practical developer news, tutorials, and tools read by millions of developers worldwide.","inLanguage":"en-US","isPartOf":{"@id":"https://daily.dev/#website"}},{"@type":"Article","@id":"https://daily.dev/blog/using-regular-expressions-in-javascript/#article","headline":"🎯 Using Regular Expressions in JavaScript","url":"https://daily.dev/blog/using-regular-expressions-in-javascript/","datePublished":"2020-04-02","dateModified":"2026-05-15T14:26:37.480Z","isPartOf":{"@id":"https://daily.dev/#website"},"publisher":{"@id":"https://daily.dev/#organization"},"mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/blog/using-regular-expressions-in-javascript/"},"description":"Learn the use of regular expressions and regex in JavaScript. Explore practical developer news, tutorials, and tools read by millions of developers worldwide.","image":{"@type":"ImageObject","url":"https://media.daily.dev/image/upload/s--Clr2VYHk--/f_auto,q_auto/v1/recruiter-landing/5ef3ba37b75de71b0399c805_8gbjyb9iyrmsghn9aqrp_5e7c86e47e?_a=BAMAMiB80"},"author":{"@type":"Person","name":"Saqib Ameen","url":"https://twitter.com/saqibameen"},"potentialAction":{"@type":"ReadAction","target":"https://daily.dev/blog/using-regular-expressions-in-javascript/"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://daily.dev/blog/"},{"@type":"ListItem","position":3,"name":"Webdev","item":"https://daily.dev/categories/webdev/"},{"@type":"ListItem","position":4,"name":"🎯 Using Regular Expressions in JavaScript","item":"https://daily.dev/blog/using-regular-expressions-in-javascript/"}]}]}
```

