Learn JavaScript Regex Testing: Simple Examples

Learn JavaScript Regex Testing: Simple Examples

Regular expressions (regex) are powerful tools for pattern matching within strings. They can seem daunting at first, but with a solid understanding of the basics and practice, you’ll quickly become proficient. This article focuses on testing JavaScript regexes, providing simple, clear examples to guide you.

1. The Basics: What is a Regex?

A regular expression is a sequence of characters that defines a search pattern. In JavaScript, regexes are objects. You can create them in two ways:

  • Literal Notation: Enclosed in forward slashes (/pattern/).
  • Constructor Function: Using the RegExp constructor (new RegExp('pattern')).

Both achieve the same result, but literal notation is generally preferred for readability and performance when the pattern is known at compile time. The constructor is useful when the pattern is dynamically generated.

2. Testing Methods in JavaScript

JavaScript provides several methods for testing if a string matches a regular expression. The two most common are test() and exec().

  • test() (RegExp method): This is the simplest and most common method. It returns true if the string matches the regex, and false otherwise. It’s a boolean check.

  • exec() (RegExp method): This method returns an array containing the matched text and related information if a match is found, or null if no match is found. It provides more detail than test().

  • match() (String method): Similar to exec(), it returns an array of matches, or null if no match is found. Crucially, match()‘s behavior changes depending on the presence of the global flag (g).

  • matchAll() (String Method) Returns an iterator of all results matching a string against a regular expression, including capturing groups.

  • search() (String Method) Tests for a match in a string. It returns the index of the match, or -1 if the search fails.

3. Simple Examples: test()

Let’s start with the most basic examples using the test() method.

“`javascript
// Example 1: Check for the presence of the word “hello”
const regex1 = /hello/; // Literal notation
const str1 = “Hello world!”;
const str2 = “Goodbye world!”;

console.log(regex1.test(str1)); // Output: false (case-sensitive)
console.log(regex1.test(str2)); // Output: false

// Example 2: Case-insensitive search (using the ‘i’ flag)
const regex2 = /hello/i; // ‘i’ flag for case-insensitivity
console.log(regex2.test(str1)); // Output: true
console.log(regex2.test(str2)); // Output: false

// Example 3: Check for any digit (using the ‘\d’ character class)
const regex3 = /\d/; // ‘\d’ matches any digit (0-9)
const str3 = “abc123xyz”;
const str4 = “abcdefg”;

console.log(regex3.test(str3)); // Output: true
console.log(regex3.test(str4)); // Output: false

// Example 4: Check for a specific sequence of digits
const regex4 = /123/;
console.log(regex4.test(str3)); // Output: true
console.log(regex4.test(str4)); // Output: false

// Example 5: Check for the start of a string (using the ‘^’ anchor)
const regex5 = /^Hello/; // ‘^’ matches the beginning of the string
const str5 = “Hello, how are you?”;
const str6 = “Well, Hello there!”;

console.log(regex5.test(str5)); // Output: true
console.log(regex5.test(str6)); // Output: false

// Example 6: Check for the end of a string (using the ‘$’ anchor)
const regex6 = /there!$/; // ‘$’ matches the end of the string
console.log(regex6.test(str5)); // Output: false
console.log(regex6.test(str6)); // Output: true

// Example 7: Using the RegExp constructor
const regex7 = new RegExp(“world”);
const str7 = “Hello world”;
console.log(regex7.test(str7)); // Output: true
“`

4. Simple Examples: exec()

Now, let’s explore exec(), which provides more information about the match.

“`javascript
// Example 8: Finding the first match of “world”
const regex8 = /world/;
const str8 = “Hello world! Goodbye world!”;
const result8 = regex8.exec(str8);

console.log(result8);
// Output:
// [
// ‘world’,
// index: 6,
// input: ‘Hello world! Goodbye world!’,
// groups: undefined
// ]

// Explanation:
// – ‘world’: The matched substring.
// – index: The starting index of the match within the string.
// – input: The original string that was tested.
// – groups: This would contain named capture groups (if defined in the regex).

// Example 9: No match found
const regex9 = /mars/;
const str9 = “Hello world!”;
const result9 = regex9.exec(str9);

console.log(result9); // Output: null

// Example 10: Using the ‘g’ (global) flag with exec()
const regex10 = /world/g; // ‘g’ flag for global search
const str10 = “Hello world! Goodbye world!”;
let result10;

while ((result10 = regex10.exec(str10)) !== null) {
console.log(Found "${result10[0]}" at index ${result10.index});
}
// Output:
// Found “world” at index 6
// Found “world” at index 22

// Explanation:
// With the ‘g’ flag, exec() can be used in a loop to find all matches.
// Each call to exec() updates the regex object’s lastIndex property,
// so the next search starts from that position.
“`

5. Simple Examples: match()

“`javascript
// Example 11: Using match() without the global flag
const regex11 = /world/;
const str11 = “Hello world! Goodbye world!”;
const result11 = str11.match(regex11);
console.log(result11); // Output similar to exec() without ‘g’

// Example 12: Using match() with the global flag
const regex12 = /world/g;
const str12 = “Hello world! Goodbye world!”;
const result12 = str12.match(regex12);
console.log(result12); // Output: [ ‘world’, ‘world’ ] – An array of all matches.

// Example 13: match() with no matches
const regex13 = /mars/;
const str13 = “Hello world!”;
const result13 = str13.match(regex13);
console.log(result13); // Output: null
“`

6. Simple Examples: matchAll()
“`javascript
const regexp = /t(e)(st(\d?))/g;
const str = ‘test1test2’;

const array = […str.matchAll(regexp)];

console.log(array[0]);
// Expected output: Array [“test1”, “e”, “st1”, “1”]

console.log(array[1]);
// Expected output: Array [“test2”, “e”, “st2”, “2”]
“`

7. Simple Examples: search()

“`javascript

//Example 14 Using search()
const paragraph = ‘The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?’;

// Any character that is not a word character or whitespace
const regex = /[^\w\s]/g;

console.log(paragraph.search(regex));
// Expected output: 43

console.log(paragraph[paragraph.search(regex)]);
// Expected output: “.”
“`

8. Common Character Classes and Quantifiers

These are essential building blocks for your regex patterns:

  • . (dot): Matches any character except a newline.
  • \d: Matches any digit (0-9). Equivalent to [0-9].
  • \w: Matches any “word” character (alphanumeric and underscore). Equivalent to [a-zA-Z0-9_].
  • \s: Matches any whitespace character (space, tab, newline, etc.).
  • [abc]: Matches any one of the characters ‘a’, ‘b’, or ‘c’.
  • [^abc]: Matches any character except ‘a’, ‘b’, or ‘c’.
  • [a-z]: Matches any lowercase letter from ‘a’ to ‘z’.
  • [A-Z]: Matches any uppercase letter from ‘A’ to ‘Z’.
  • [0-9]: Matches any digit from 0 to 9.
  • ?: Matches the preceding character zero or one time (optional).
  • *: Matches the preceding character zero or more times.
  • +: Matches the preceding character one or more times.
  • {n}: Matches the preceding character exactly n times.
  • {n,}: Matches the preceding character n or more times.
  • {n,m}: Matches the preceding character between n and m times (inclusive).
  • ^: Matches the beginning of the string (or line, if multiline mode is enabled).
  • $: Matches the end of the string (or line, if multiline mode is enabled).
  • |: Acts like a boolean OR. Matches the expression before or after the |.
  • (): Creates a capturing group. You can extract the text matched by the group.

9. Combining Concepts

Let’s combine these to create more complex (but still relatively simple) regexes:

“`javascript
// Example 15: Validate a simple email address (very basic!)
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9.-]+$/;
const email1 = “[email protected]”;
const email2 = “invalid-email”;
const email3 = “[email protected]”;

console.log(emailRegex.test(email1)); // Output: true
console.log(emailRegex.test(email2)); // Output: false
console.log(emailRegex.test(email3)); // Output: true

// Example 16: Find all numbers in a string
const numRegex = /\d+/g; // One or more digits, globally
const numStr = “There are 12 apples and 3 oranges.”;
const numResult = numStr.match(numRegex);

console.log(numResult); // Output: [ ’12’, ‘3’ ]

// Example 17: Check for a 5-digit US ZIP code
const zipRegex = /^\d{5}$/;
const zip1 = “90210”;
const zip2 = “1234”;
const zip3 = “90210-1234”; // Will fail, we’re only checking for 5 digits

console.log(zipRegex.test(zip1)); // Output: true
console.log(zipRegex.test(zip2)); // Output: false
console.log(zipRegex.test(zip3)); // Output: false

// Example 18: Capture parts of a date (YYYY-MM-DD)
const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
const dateStr = “2023-10-27”;
const dateResult = dateRegex.exec(dateStr);

if (dateResult) {
console.log(“Year:”, dateResult[1]); // Output: Year: 2023
console.log(“Month:”, dateResult[2]); // Output: Month: 10
console.log(“Day:”, dateResult[3]); // Output: Day: 27
}
“`

10. Key Takeaways and Best Practices

  • Start Simple: Begin with basic patterns and gradually increase complexity.
  • Test Frequently: Use test(), exec(), or online regex testers (like Regex101, RegExr) to verify your patterns.
  • Be Specific: Avoid overly broad patterns that might match unintended text.
  • Use Character Classes: \d, \w, \s are your friends!
  • Understand Quantifiers: ?, *, +, {} control repetition.
  • Use Anchors: ^ and $ are crucial for matching the start/end of strings.
  • Escape Special Characters: If you want to match a literal . or *, you need to escape it with a backslash (e.g., \., \*).
  • Read the Documentation: The MDN Web Docs are an excellent resource for JavaScript regexes.
  • Comment your Regex: Complex regexes can be hard to understand, so comment them well.

This article provides a foundation for working with JavaScript regex testing. Practice these examples, experiment with different patterns, and you’ll soon be comfortable using regexes to solve a wide range of string manipulation problems. Remember to break down complex problems into smaller, manageable parts, and use the testing methods to ensure your regex behaves as expected.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top