1

How can I extract properties and values from CSS stylesheet inside string.

Example:

var strCSS = ".box{background: red; color: white;}";

How can I extract the "background" property's value from the above line, knowing that I want to use it with complex CSS stylesheet.

4 Answers 4

3

Using the CSSStyleSheet API, you can get the values without having to hack away with awful regular expressions and finicky string manipulations:

var strCSS = '.box{background: red; color: white;}';

function getValue(css, selector, property) {
  var style = document.createElement('style');
  style.appendChild(document.createTextNode(css));
  document.body.appendChild(style);
  var sheet = style.sheet;
  style.remove();
  var rule = Array
    .from(sheet.cssRules)
    .find(cssRule => cssRule.selectorText === selector);

  if (rule) {
    return rule.style.getPropertyValue(property);
  }
}

console.log(getValue(strCSS, '.box', 'background'));
<style>.box{background: red; color: white;}</style>

Sign up to request clarification or add additional context in comments.

3 Comments

While regular expressions might seem hacky, CSS has simple rules to follow and you don't have to mess with the DOM to get a simple string.
@TomášVarga Regular expressions would not be able to handle every single hypothetical selector like .box[id="{background:blue;"] { background: red; } now, would they?
@PatrickRoberts thought about it as just a quick and dirty way, imho this example seems too theoretical (btw the last example of my answer works)
0

While a bit more cryptic, regular expressions are a possible approach:

var match = strCSS.match(/background:\s*([^;}]*)/)
var background = match[1]

or as one-liner

var background = strCSS.replace(/^.*background:\s*([^;}]*)[;}].*$/, '$1')

or with dynamically set property name

var propName = 'background';
var propRegex = new RegExp('^.*' + propName + ':\\s*([^;}]*)[;}].*$');
var propVal = strCSS.replace(propRegex, '$1')

1 Comment

I would love your solution if you didn't have to hardcode "background" into the regular expression, it would also be more useful if you could get all the properties.
0

Here is a simple solution that uses no regular expressions:

const extractProperties = function extractProperties(str) {
  return str 
.substring(strCSS.indexOf('{') + 1, strCSS.indexOf('}'))
.split(";")
.map((el) => el.substring(0, el.indexOf(':')).trim())
.filter(Boolean);
};

const strCSS = ".box:hover {background: red; color: white; transform: translate(50%, 50%); font-family: arial}";
console.log(extractProperties(strCSS));

A slight variant of this function, because I only realize now that it is the values you want (not my mistake, you said "how can I get 'background' property"):

const extractValues = function extractValues(str) {
  return str 
.substring(strCSS.indexOf('{') + 1, strCSS.indexOf('}'))
.split(";")
.map((el) => el.substring(el.indexOf(':') + 1, el.length).trim())
.filter(Boolean);
};

const strCSS = ".box:hover {background: red; color: white; transform: translate(50%, 50%); font-family: arial}";
console.log(extractValues(strCSS));

1 Comment

As of the question's current "wording", my answer is the only correct solution (not that it is what OP wants, now that I understand the situation).
0

Getting CSS values in JavaScript is relatively simple:

console.log( document.getElementById("foo").style.background );

If you must extract it from a string, then I'd recommend the following:

// Split CSS string into each individual property
strCSS = strCSS.split(";");

// For each property/value pair...
for (var i = 0; i < strCSS.length; i++) {

    // Split into property and value
    strCSS[i] = strCSS[i].split(":");

    // Get background value
    if (strCSS[i][0] == "background") {
        return strCSS[i][1];
    }
}

That should work.

3 Comments

I think he is asking how to extract css from a css file
BTW no need to break; after return. And you've missed a closing }.
You have to run that snippet on the string between the { and } in the original strCSS - I forgot to clarify that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.