# JavaScript Regex Basics: Literals, Flags, and Core Syntax

Source: https://devdocs10.com/articles/javascript/js-regex-basics  
By Murat Bo · Published 2026-06-28 · DevDocs10 (https://devdocs10.com)

Regular expressions let you describe text patterns in JavaScript, so you can search, validate, extract, and replace text with less manual string logic. This article focuses on the basics: regex literals, the most common flags, and the core ideas you need to read and write simple patterns confidently.

> **Quick answer:** In JavaScript, a regex literal looks like `/pattern/flags`. Use it when the pattern is known ahead of time, and add flags like `i` for case-insensitive matching or `g` for global search.

> **Difficulty:** Beginner
>
> **You'll understand this better if you know:** basic JavaScript strings, how methods like `test()` and `match()` work, and the idea of comparing text to a pattern instead of an exact value.

## 1. What Is JavaScript Regex Basics?

Regex basics are the small set of rules you use to create and read regular expressions in JavaScript. A regular expression is a pattern object that matches text according to rules you define, rather than comparing a string exactly.

- A regex can find whether text contains a pattern.
- A regex can validate the shape of input, such as an email-like string or a ZIP code format.
- A regex can extract parts of a string, such as a file extension or date fragment.
- A regex can replace matching text with new text.

In JavaScript, you usually write regexes either as a literal like `/cat/i` or with the `RegExp` constructor like `new RegExp("cat", "i")`.

## 2. Why JavaScript Regex Basics Matter

Regex gives you a compact way to solve common text problems that would otherwise require a lot of string splitting, looping, and manual checks. Even a few basic regex skills can make input validation and text parsing much easier.

You will use regex when you want to:

- check whether a username contains allowed characters,
- search logs or content for a keyword pattern,
- clean up extra spaces, punctuation, or formatting,
- extract values from formatted text such as IDs or dates.

It is also important to know the basics because many JavaScript APIs use regex directly, including `String.prototype.match()`, `replace()`, `search()`, and `split()`.

## 3. Basic Syntax

A regex literal has two slashes around the pattern, followed by optional flags.

### Regex literal form

```javascript
const pattern = /cat/i // matches "cat", "Cat", "CAT", and so on
```

The part between the slashes is the pattern. The letters after the second slash are flags that change how matching works.

### Using the RegExp constructor

```javascript
const pattern = new RegExp("cat", "i") // same idea as /cat/i
```

You usually choose the literal form when the pattern is fixed in your source code. Use the constructor when you need to build the pattern from a variable.

### How matching works

JavaScript compares the pattern to a string and returns a result based on the method you call. For example, `test()` returns a Boolean, while `match()` returns matched text information.

```javascript
const word = "Cat";
const isMatch = /cat/i.test(word);
```

This example shows the pattern `/cat/i` matching `"Cat"` because the `i` flag ignores case.

## 4. Step-by-Step Examples

### Example 1: Check whether a string contains a word

This is the simplest use of a regex: test whether a pattern exists anywhere in a string.

```javascript
const text = "I like JavaScript";
const hasScript = /script/i.test(text);

// hasScript is true
```

The `i` flag makes the match case-insensitive, so the pattern matches `"Script"` even though the pattern is lowercase.

### Example 2: Match a start-of-string prefix

The `^` symbol means “start of the string” in a regex.

```javascript
const filename = "report.pdf";
const startsWithReport = /^report/.test(filename);
```

This pattern only matches if the text begins with `report`. Without `^`, the word could appear anywhere in the string.

### Example 3: Find all digit groups

The `g` flag asks JavaScript to find every match instead of stopping after the first one.

```javascript
const value = "Order 12 costs 45 dollars";
const numbers = value.match(/\d+/g);

// numbers is ["12", "45"]
```

The token `\d` means a digit, and `+` means one or more of the previous token. Together, they match each number in the string.

### Example 4: Use a pattern built from a variable

Sometimes the pattern comes from user input or another variable. In that case, the constructor can be useful.

```javascript
const term = "dog";
const pattern = new RegExp(term, "i");

const result = pattern.test("A Dog ran past");
```

This works like a literal regex, but the pattern text is supplied dynamically. For fixed patterns, the literal form is usually easier to read.

## 5. Practical Use Cases

Regex basics are useful in many everyday JavaScript tasks.

- Validating that a form field contains a simple pattern, such as digits only or letters plus spaces.
- Checking whether a log line contains a level such as `ERROR` or `WARN`.
- Extracting file extensions from names like `photo.jpg` or `archive.tar.gz`.
- Replacing repeated whitespace with a single space.
- Splitting text into parts when a delimiter may be more complex than one exact character.

For example, a simple username check can use a regex instead of manual character-by-character validation.

## 6. Common Mistakes

### Mistake 1: Forgetting that regex literals use slashes

Beginners sometimes write the pattern text as if it were a plain string or forget the closing slash. JavaScript then does not see a valid regex literal.

**Problem:** This is not a valid regex literal because it is missing the regex delimiters.

```javascript
const pattern = cati;
```

**Fix:** Wrap the pattern in slashes and place flags after the second slash.

```javascript
const pattern = /cat/i;
```

The corrected version works because JavaScript recognizes it as a regex literal, not as a normal identifier or string.

### Mistake 2: Confusing `g` with `i`

The `g` flag means global matching, not case-insensitive matching. The `i` flag handles case differences.

**Problem:** This pattern will only find lowercase `cat` because `g` does not ignore case.

```javascript
const found = /cat/g.test("Cat");
```

**Fix:** Use `i` when you want to ignore case. Add `g` only if you also need every match.

```javascript
const found = /cat/i.test("Cat");
```

The fixed version works because the `i` flag makes the comparison case-insensitive.

### Mistake 3: Expecting `match()` to behave the same with and without `g`

With `g`, `match()` returns an array of all matches. Without `g`, it returns more detailed match information for the first match only.

**Problem:** This code expects the first capture data, but the global flag changes the shape of the result.

```javascript
const text = "a1 b2 c3";
const match = text.match(/\d+/g);
const first = match[1];
```

**Fix:** If you want the first match details, remove `g`. If you want all matches, use the returned array correctly.

```javascript
const text = "a1 b2 c3";
const matches = text.match(/\d+/g);
const first = matches[0];
```

The corrected version works because it matches the code to the actual return value shape.

## 7. Best Practices

### Practice 1: Use regex literals for fixed patterns

When the pattern is known in advance, a literal is shorter and easier to read than the constructor.

```javascript
const emailLike = /@/;
```

This approach makes the pattern obvious at the point of use and avoids extra quoting rules.

### Practice 2: Use flags intentionally, not by habit

Choose a flag only when you need what it changes. This keeps patterns easier to understand and avoids surprising results.

```javascript
const text = "One ONE one";
const allWords = text.match(/one/gi);
```

Here, `g` finds every occurrence and `i` ensures mixed case still matches.

### Practice 3: Keep validation patterns simple

Basic regex is best for simple rules. If the validation becomes too complex, break it into smaller checks so the code stays maintainable.

```javascript
const zipCode = "12345";
const isZip = /^\d{5}$/.test(zipCode);
```

This example checks a simple five-digit format without adding unnecessary complexity.

## 8. Limitations and Edge Cases

- Regex literals are created when JavaScript parses the file, so syntax mistakes cause immediate parse errors.
- The `g` flag can make some regex methods behave differently, especially `match()` and repeated calls to `test()` with the same pattern instance.
- Special characters such as `.`, `*`, `?`, `+`, `(`, and `[` have meaning in regex and usually must be escaped when you want them literally.
- A regex checks a pattern, not full semantic correctness. For example, a simple email regex can accept invalid addresses or reject valid ones.
- Some escapes and behaviors depend on flags such as `u`, which affects Unicode handling.

If you see `Invalid regular expression`, it usually means the pattern syntax itself is broken, such as an unmatched bracket or parenthesis.

## 9. Practical Mini Project

Let’s build a tiny text checker that finds whether a note contains a four-digit year and normalizes extra spaces. This combines the basic ideas of literals, flags, and simple matching.

```javascript
const note = "  Meeting in 2024   with the team  ";

const hasYear = /\b\d{4}\b/.test(note);
const cleaned = note.replace(/\s+/g, " ").trim();

console.log(hasYear);
console.log(cleaned);
```

Output (tested with Node 24.21.0):

```text
true
Meeting in 2024 with the team
```

This mini project shows two common regex jobs: checking whether a pattern exists and using a global replacement to clean formatting. The expected output is `true` and `"Meeting in 2024 with the team"`.

## 10. Key Points

- A regex literal uses `/pattern/flags`.
- Use `i` for case-insensitive matching and `g` for global matching.
- Use `test()` for Boolean checks and `match()` when you want match results.
- Escape special characters when you mean them literally.
- Keep your first regexes simple and focused on one task at a time.

## 11. Practice Exercise

- Write a regex that matches the word `code` in any case.
- Use it to check whether each string contains the word: `"code"`, `"Code"`, and `"codec"`.
- Expected output: the first two should match, and the third should not match if you require the whole word.

**Hint:** Use word boundaries with `\b` and the `i` flag.

**Solution:**

```javascript
const pattern = /\bcode\b/i;

const samples = ["code", "Code", "codec"];

for (const sample of samples) {
  console.log(sample, pattern.test(sample));
}
```

Output (tested with Node 24.21.0):

```text
code true
Code true
codec false
```

This solution works because `\b` keeps the pattern focused on the full word, while `i` ignores letter case.

## 12. Final Summary

JavaScript regex basics start with a simple but powerful idea: describe text with a pattern instead of comparing it character by character. The most common starting point is the regex literal form, `/pattern/flags`, which is concise and easy to read once you understand the slashes and flags.

The two flags most beginners use first are `i` for case-insensitive matching and `g` for matching all occurrences. From there, you can combine regexes with methods like `test()`, `match()`, and `replace()` to solve real string-processing tasks.

As you continue, focus on small patterns, learn the most common special symbols, and test your regexes against real strings. A steady approach will make regular expressions much easier to read and much more useful in everyday JavaScript code.
