Skip to content Skip to sidebar Skip to footer

D3.js If Else Regex String Match To Change Style

I have the following string in a column(col2) in a csv file: 'unserer {m}, unsere {p} and {f}, unseres {n} I would like to color the background of the words preceeding {m|f|n} b

Solution 1:

d3.select("#sentence").html(d.col2)
    .style({ "background-color": "blue" })
    .filter(function () {
        return d.col2.match(/.*\w+\s\{f\}/)
    })
    .style({ "background-color": "red" })

If you actually want to style the paragraphs and set their content and then the styles, it would be better to use classes instead of id. So something like

<divclass="sentence"></div><divclass="sentence"></div>

would have the script as

d3.selectAll(".sentence").data(d).html(function (d) {
        return d.col2
    })
    .style("background-color", function(d) {
        if ( d.col2.match(/.*\w+\s\{f\}/) ) {
            return"red"
        } else {
            return"blue"
        };
    });

If you actually want to style the paragraphs

d3.selectAll(".sentence").data(d).html(function (d) {
        return d.col2
    })
    .style("background-color", function(d) {
        if ( d.col2.match(/.*\w+\s\{f\}/) ) {
            return"red"
        } else {
            return"blue"
        };
    });

with the data d as

var d = [
    {
        col2: "your data"
    },
    {
        col2: "more of your data"
    },
    {
        col2: "and here's some more"
    }
]

Solution 2:

I'm assuming you have data bound to the element with id of sentance. If so, it's as simple as:

 d3.select('#sentance')
    .style("background-color", function(d){
      return d.col2.match(/.*\w+\s\{f\}/) ? "red" : "blue";
    });

Working example:

<!DOCTYPE html><html><head><scriptdata-require="d3@3.5.3"data-semver="3.5.3"src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script><linkrel="stylesheet"href="style.css" /><scriptsrc="script.js"></script></head><body><divid="sentance">Now is the winter of our discontent.</div><script>
      d3.select('#sentance')
        .datum({col2: "somestring"})
        .style("background-color", function(d){
          return d.col2.match(/.*\w+\s\{f\}/) ? "red" : "blue";
        })
      
    </script></body></html>

Post a Comment for "D3.js If Else Regex String Match To Change Style"