Hi everyone,
So I am writing a function that loops through the classes of an element and returns an object based on if those classes match a reg expression.
HTML
<ul>
<li id="el" class="item-red-true item-blue-false item-green-true">Element</li>
</ul>
JS
const colorObj = {
red: true,
blue: true,
green: true
};
const el = document.getElementById('el');
const classArray = [...el.classList];
classArray.forEach((item)=>{
const regex = /^item-(red|blue|green)-(true|false)/gm;
const regexSplit = regex.exec(item);
colorObj[`${regexSplit[1]}`] = regexSplit[2];
console.log(regexSplit);
console.log(colorObj);
});
This code works as I would like it to and is console.logging the correct colorObj. But ideally I would like to be able to loop through the keys of the color obj and check if the classes match the format item-${key}-(true|false);
I have tried doing something like this:
const colorObj = {
red: true,
blue: true,
green: true
};
const el = document.getElementById('el');
const classArray = [...el.classList];
classArray.forEach((item)=>{
Object.keys(colorObj).forEach(function (key) {
const regex = new RegExp(`^item-(${key})-(true|false)`,'gm');
const regexSplit = regex.exec(item);
colorObj[`${regexSplit[1]}`] = regexSplit[2];
console.log(regexSplit);
console.log(colorObj);
});
});
but it didn’t work? Any tips on what I’m doing wrong?