DEV Community

Yoshiro Matsumoto
Yoshiro Matsumoto

Posted on

Selector2Regexp - generating regular expressions from CSS selectors

"Selector2Regexp" is a tiny tool that I released recently.
It generates regular expressions of JavaScript from CSS selectors. The regular expressions are used for searching HTML elements matching with a given CSS selector.

Features

  • It generates regular expressions using CSS Selectors.
  • Commonly used selectors and combinators are supported.

Usage

It is very straightforward.
Only you have to do is to look up an html tag which is referenced by JavaScript or CSS.

$ npm i selector-2-regexp

$ s2r '.button'
# => <\s*([a-zA-Z]+)\s+.*(class=(?=['"])((?=(.*[\s'"]button[\s'"])).*)(?=['"])).*\s*>

With clipboard

It's convenient if you use it with any editor tools.

  1. Save the result to clipboard.

    $ s2r '.button' | pbcopy
    
  2. paste it on a search input of a editor(e.g. VS Code)
    Alt Text

Motivation

I often refactor my frontend codes everyday and I have to look up a html tag which is referenced by JavaScript or CSS.
I think that regular expression could be a better way to do that frequently but It was difficult for me to remember how to use them. I needed an easy way to achieve it.
That is why I made Selector2Regexp.

I hope this tool will help you.

https://github.com/m-yoshiro/Selector2Regexp

Top comments (0)