What is the REGEX of a CSS selector

前端 未结 9 2033
你的背包
你的背包 2021-02-02 12:27

I\'d like to parce a CSS file and add before every CSS selector another selector.

From:

p{margin:0 0 10px;}
.lead{margin-bottom:20px;font-size:21px;font-         


        
9条回答
  •  抹茶落季
    2021-02-02 13:10

    While it isn't possible to write a single regular expression that matches any valid CSS selector, you can combine a couple regular expressions and a bit of logic to accomplish your goal.

    The following uses Node's fs module to read the CSS, but you could get the raw CSS string however you want.

    const fs = require('fs'),
        myClassName = 'mySelector',
        mySelector = '.' + myClassName,
        mySelectorRegex = new RegExp(`\\.${myClassName}([ .#[:(]|$)`),
        cssSelectorRegex = /[@.#a-zA-Z][^}]*?(?={)/g;
    
    let css = fs.readFileSync('path/to/file.css').toString();
    
    css = css.replace(cssSelectorRegex, match => {
    
        // Match is a string of selectors like '.foo' or '.foo, #bar'
        // We need to split it on the comma and handle each selector individually
        return match.split(',').map(selector => {
    
            selector = selector.trim();
    
            // Don't alter media queries, imports, or selectors that already contain '.mySelector'
            if (selector.startsWith('@') || selector.match(mySelectorRegex)) {
    
                return selector;
    
            }
    
            // Prepend '.mySelector ' to the selector
            return mySelector + ' ' + selector;
    
        // Combine the list of selectors back together
        }).join(',');
    
    });
    

提交回复
热议问题