MDN Blog: JavaScript regular expressions reference docs

2023-05-24-mdn-blog-javascript-regex-reference.md

The JavaScript regular expressions (regex) documentation had a big update recently thanks to the efforts of Joshua Chen. Josh did the heavy lifting, and I was glad to give some feedback and reviews to land the changes. There are new, dedicated pages for each JS language feature for regular expressions, with information about the syntax and browser compat data, too.

MDN Blog, JavaScript regular expressions

If you want to see everything that’s changed, we published a post on the MDN Blog that covers highlights and specifics of what’s been updated. Check it out if you want to read the guides for creating regular expressions in JavaScript and other pages that cover:

  • flags that change how a regex is interpreted
  • assertions to check if a pattern matches a condition (e.g., start of a string)
  • atoms - the units that make up a regex pattern
  • other features like quantifiers (*, +, ? etc.) that help you compose patterns

Out of the examples, I highlighted a few in the blog post that I thought were nice and are useful for certain purposes. The one below is nice because it detects strings in specific scripts or writing systems without having to exhaustively specify the characters or ranges of characters that make a script:

const mixedCharacters = "aεЛ";
// I could write out everything ...
// mixedCharacters.match(/[ΑαΒβΓγΔδΕεΖζΗηΘθΙιΚκΛλ... <-- oh no

// Or use a short alias for Greek instead:
mixedCharacters.match(/\p{Script=Grek}/u); // ε
// Or a short name
mixedCharacters.match(/\p{sc=Cyrillic}/u); // Л

GitHub PRs updating JS regex

Here’s the two main GitHub PRs that we worked on to add the updates:

For the Browser Compat Data, I had to cover a lot of cases across multiple browsers and operating systems. I did this using Browserstack with a codepen like the one below so I could visually check for matches as a kind of smoke test. Of course, you could do asserts with test() and fully automate this headlessly, but this was the quickest way to check for passing cases and fill in the blanks:

If you’re getting started with JavaScript and regular expressions, I hope these resources make the topic a little less scary. Let me know what you think or if I missed anything below or get in touch on Mastodon. Happy /pattern|matching/!

Published: