0

I get this string:

    arguments: {[

    { style: "fill: red; stroke-width: 1; stroke: black;" }
]}

I want to get the value of a specific attribute. I can already end up with the value of the style.

"fill: red; stroke-width: 1; stroke: black;"

I'm thinking to convert this to an array or a json so I can just search for the key. But I'm not really sure how to do it.

1
  • are you passing the style attribute or you are getting from some source? Commented Jul 2, 2014 at 16:42

4 Answers 4

2

One line solution

var s="fill: red; stroke-width: 1; stroke: black;";
var dict = {}
s.split(";").map(function (e){ if (e) {var parts = e.split(":"); dict[parts[0].trim()] = parts[1].trim()  }})
//dict = {fill: "red", stroke-width: "1", stroke: "black"}
Sign up to request clarification or add additional context in comments.

Comments

2

Split the string into styles based on ;, then split those based on ::

var ss = "fill: red; stroke-width: 1; stroke: black;";
var styles = {};

var parts = ss.split(/\s*;\s*/);

for ( var i = 0; i < parts.length; ++i )
  {
    var vv = parts[i].split(/\s*:\s*/);

    if (vv.length == 2)
      styles[vv[0]] = vv[1];
  }

After which, styles will contain:

{
  'fill': 'red',
  'stroke': 'black',
  'stroke-width': '1'
}

And can be accessed as:

console.log(styles['fill']); // etc.

Comments

0

You could actually create an element and make this its style attribute, then check a particular style -- but as long as the string is consistently well-formatted using split will work.

var styles = arguments[0].style.split(";");
styles.forEach(function (style) {
    var pair = style.split(":");
    if (pair[0] == "fill") {
        pair[1] == "red";
    }
});

Comments

0

To simply search for the value with a key, you don't need to convert it into an object. Here's an example:

var str = "fill: red; stroke-width: 1; stroke: black;",
    key = "fill";

str.match(new RegExp(key+": "+"([^;]+);"))[1];   //"red"

Comments

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.