DEV Community

Cover image for Human Regex Gets TypeScript's Magic Typing ๐Ÿš€
Ridwan Ajibola
Ridwan Ajibola

Posted on

2

Human Regex Gets TypeScript's Magic Typing ๐Ÿš€

Two weeks ago, I released the first public version of Human Regex, and Iโ€™m thrilled to share that it now leverages TypeScriptโ€™s magic typing to take regex building to the next level! This update not only brings a host of bug fixes but also introduces a smarter, safer API for crafting regular expressions. Thanks to two new contributorsโ€”one of whom contributed the powerful magic typingโ€”Human Regex has already gained 900+ downloads.

Why is Human Regex better than traditional regex in JS/TS?

  • English-like Syntax: Build regex patterns in a readable, chainable syntax that feels like natural language.
  • Magic Typing: Enforces valid regex construction at compile time, catching mistakes early and making your code safer.

Want to Learn More?

  • ๐Ÿ”Ž Missed the gist, check out my previous blog post.
  • ๐Ÿ“˜ Explore the latest tutorial: Dive deeper into using Human Regex in your JS/TS projects by completing this blog post.

Getting Started

Installation:
Start by installing Human Regex in your project:

npm install human-regex
Enter fullscreen mode Exit fullscreen mode

Then import the library in your TypeScript code:

import { createRegex } from "human-regex";
Enter fullscreen mode Exit fullscreen mode

Simple Examples:

Basic Literal Match:
Match the exact word "hello" without worrying about special character escaping.

const helloRegex = createRegex()
.literal("hello")
.toRegExp();

console.log(helloRegex.test("hello")); // true
console.log(helloRegex.test("world")); // false
Enter fullscreen mode Exit fullscreen mode

Digit Matching:
Create a regex that matches only digits.

const digitRegex = createRegex()
  .digit()
  .toRegExp();

console.log(digitRegex.test("5")); // true
console.log(digitRegex.test("a")); // false
Enter fullscreen mode Exit fullscreen mode

Using the OR Operator:
Match one of multiple options using the .or() method.

const animalRegex = createRegex()
  .literal("cat")
  .or()
  .literal("dog")
  .toRegExp();

console.log(animalRegex.test("cat")); // true
console.log(animalRegex.test("dog")); // true
console.log(animalRegex.test("bat")); // false
Enter fullscreen mode Exit fullscreen mode

Whitespace Matching:
Check if a string contains a whitespace character.

const whitespaceRegex = createRegex()
  .whitespace()
  .toRegExp();

console.log(whitespaceRegex.test(" ")); // true
console.log(whitespaceRegex.test("a")); // false
Enter fullscreen mode Exit fullscreen mode

Escaping Special Characters:
The .literal() method automatically escapes special characters for you.

const specialCharsRegex = createRegex()
  .literal(".*+?^${}()|[]\\")
  .toRegExp();

console.log(specialCharsRegex.test(".*+?^${}()|[]\\")); // true
Enter fullscreen mode Exit fullscreen mode

Protocol Validation:
Build a regex to check for a valid HTTP/HTTPS protocol.

const protocolRegex = createRegex()
  .protocol()
  .toRegExp();

console.log(protocolRegex.test("http://"));  // true
console.log(protocolRegex.test("https://")); // true
console.log(protocolRegex.test("ftp://"));   // false
Enter fullscreen mode Exit fullscreen mode

Named Capture Group:
Extract a substring using a named capture group.

const namedGroupRegex = createRegex()
  .startNamedGroup("digits")
    .digit()
    .oneOrMore()
  .endGroup()
  .literal("-end")
  .toRegExp();

const match = "12345-end".match(namedGroupRegex);
if (match?.groups) {
  console.log(match.groups.digits); // "12345"
}
Enter fullscreen mode Exit fullscreen mode

Matching Exactly Three Digits:
Ensure a string contains exactly three digits.

const threeDigitsRegex = createRegex()
  .startAnchor()
  .digit()
  .exactly(3)
  .endAnchor()
  .toRegExp();

console.log(threeDigitsRegex.test("123")); // true
console.log(threeDigitsRegex.test("12"));  // false
console.log(threeDigitsRegex.test("1234")); // false
Enter fullscreen mode Exit fullscreen mode

Error Handling Examples:

Human Regex includes smart typing and runtime checks to help you catch mistakes early. Here are two examples that intentionally trigger errors:

Error Example 1: Using .lazy() on an Empty Pattern

try {
  // No quantifier exists, so calling .lazy() throws an error.
  createRegex().lazy();
} catch (e) {
  console.error(e.message); // Expected output: "No quantifier to make lazy"
}
Enter fullscreen mode Exit fullscreen mode

Error Example 2: Invalid Unicode Letter Variant

try {
  // "x" is not a valid Unicode letter variant.
  createRegex().unicodeChar("x" as any);
} catch (e) {
  console.error(e.message); // Expected output: "Invalid Unicode letter variant: x"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Human Regex transforms the complexity of traditional regex into a series of intuitive method calls. Whether youโ€™re matching a simple literal, testing digits, or combining multiple methods for complex patterns, the library offers a clear and maintainable approach. Its robust type system and runtime checks help prevent common mistakes, making your code safer and easier to debug.

Have you explored Human Regex in your projects? Iโ€™d love to hear your experiences or see your examples in the comments below!


You can also contribute by:

โญ Starring the GitHub repo to help others discover it
๐Ÿž Reporting bugs or requesting features
๐Ÿ’ก Contributing code or documentation

Happy coding!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

๐Ÿ‘‹ Kindness is contagious

Please show some love โค๏ธ or share a kind word in the comments if you found this useful!

Got it!