Mustapha Fersaoui
Mustapha Fersaoui

Reputation: 109

Extract CSS property from string using Javascript

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.

Upvotes: 1

Views: 1381

Answers (4)

Elle Nolan
Elle Nolan

Reputation: 399

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.

Upvotes: 0

doubleOrt
doubleOrt

Reputation: 2507

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));

Upvotes: 0

Tomas Varga
Tomas Varga

Reputation: 1440

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')

Upvotes: 0

Patrick Roberts
Patrick Roberts

Reputation: 51816

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>

Upvotes: 2

Related Questions