Prefix CSS selectors

Benchmark created on


Preparation HTML

<script>
  var cssText = "";
  for (var i = 0; i < 50; i += 1) {
   cssText += ".class1 { background-color: red } .class2, .class1 { color: green }";
  }
  var regular = new RegExp("([^\\s][\\s\\S]*?)(\\{[\\s\\S]*?\\})", "g");
  var prefix = ".prefix ";
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Regular expression
//Match a css rule
var match, results = [],
    selectors, prefixedSelectors;
while (match = regular.exec(cssText)) {
 //There might be a concatenation of selectors, explode them
 selectors = match[1].split(",");
 prefixedSelectors = [];

 for (var i = 0, l = selectors.length; i < l; i += 1) {
  prefixedSelectors.push(prefix + selectors[i]);
 }
 results.push(prefixedSelectors.join(","), match[2], "\n");
}

var prefixedCss = results.join("");
ready
String manipulation
var parts = cssText.split("}"),
    length = parts.length;

/* Splitting on } means that each line is a CSS rule */
var decomposed, selectors, prefixed;
for (var i = 0; i < length; i += 1) {
 decomposed = parts[i].split("{");
 selectors = decomposed[0].replace("\n", "");

 if (!selectors) {
  continue;
 }
 selectors = selectors.split(",");
 prefixed = [];

 for (var j = 0, k = selectors.length; j < k; j += 1) {
  prefixed.push(prefix + selectors[j]);
 }

 decomposed[0] = prefixed.join(",");
 parts[i] = decomposed.join("{");
}

var prefixedCss = parts.join("}\n");
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.