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-
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(',');
});