javascriptstringfilterhue

Access & Change Value Within a String in JavaScript


Quick question:

Below goes the code of a JS exercise/experiment on changing two DIV's hue values on click (#left and #right). I've managed to mostly set it up, and get it running, but I've run against a problem when both trying to access the current hue value and change that hue of the target element, as the return of e.target.style.filter is a string "(hue-rotate(Xdeg))" instead of a value.

Accessing and modifying the value within the string would allow me to increment the current e.target hue value gradually and console.log it - 360º, but I have no idea how to do that. I know how to do it externally ("hue-rotate(" + X + "deg)") but not when it comes to me already as a string.

Code goes below.

let l = 60;
let r = 60;

document.querySelectorAll('div').forEach(occurence => {
  occurence.addEventListener('click', (e) => {
    if (e.target.id == "left") {
      l += 40;
      if (l>360) {l-=360}
      e.target.style.filter = "hue-rotate(" + l + "deg)";
    }
    else if (e.target.id == "right") {
      r += 40;
      if (r>360) {r-=360}
      e.target.style.filter = "hue-rotate(" + r + "deg)";
    }
    console.log(e.target.id + " is " + e.target.style.filter);
  });
});

(For those interested, this question has been expanded to a working version of the code presented above and some additional questions on this post).


Solution

  • You can use a regular expression to extract the current value:

    const myFilter = "hue-rotate(95deg) blur(4px) ..."
    
    // the filter CSS rule can contain multiple filter-functions,
    // separated by a whitespace
    let degrees = myFilter
                     .split(" ") // split the whitespace-separated string into  an array of strings
                     .find(f => f.includes("hue-rotate")) // find the hue-rotate function
                     ?.replace(/\D/g, "") // replace all (/g) non-numerical characters (\D) with nothing ("")
    
    console.log(degrees)
    // 95