selector-2-regexp
v1.0.1-beta.6
Published
Convert CSS Selector to a Regexp string for searching matched elements in HTML.
Downloads
4
Readme
Selector2Regexp
Generate regular expressions of JavaScript from CSS selectors. That regular expressions is for searching HTML elements which is matched given CSS selector.
You can try it on the web.
https://m-yoshiro.github.io/selector2regexp-web/
Installation
$ npm i selector-2-regexp
Usage
Basic
$ s2r '.button'
# => <\s*([a-zA-Z]+)\s+.*(class=(?=['"])((?=(.*[\s'"]button[\s'"])).*)(?=['"])).*\s*>
With clipboard
Saving clipboard is convenient to use with editor, e.g. VS Code.
After saving clipboard, paste it on a search input of your editor.
Save to clipboard.
# Save to clipboard on macOS (On Windows, Replace "pbcopy" to "clip") $ s2r '.button' | pbcopy
Paste a regular expression on your tool
Examples
Basics
# Type Selector
s2r 'div'
# Classs Selector
s2r '.single'
# Id Selector
s2r '#app'
# Attribute Selector
s2r '[hidden]'
s2r '[data-state=active]'
s2r '[data-state*=active]'
s2r '[data-state~=active]'
s2r '[data-state^=active]'
s2r '[data-state$=active]'
# href, src
s2r 'a[href^=https://]'
s2r 'img[src$=.svg]'
# Multiples
s2r '.button.button--primary'
s2r 'div.panel.flex'
Combinator
# Descendant combinator
s2r '.parent .child'
# Child combinator
s2r '.parent > .child'
# Next sibling combinator
s2r '.parent + .child'
# General sibling combinator
s2r '.parent ~ .child'
Supported selectors
Basic selectors
- Class selector ✅
- ID selector ✅
- Type selector ✅
- Attribute selector ✅
Combinators
- Descendant combinator ✅
- Child combinator ✅
- General sibling combinator ✅
- Adjacent sibling combinator ✅
- Column combinator ☑️ 😢
Notes
With "combinators", a generated regular expression includes ES2018's features.
When given combinators, generated regular expressions that includes "Lookbehind assertion"
and "Negative lookbehind assertion"
which are ES2018's features.
This regular expressions might not work some environments unsupported them 😢.
(e.g., IE, FireFox and old version Node.js)
Please check their statements if you use with combinator.
https://caniuse.com/#feat=mdn-javascript_builtins_regexp_lookbehind_assertion