Shaoz Shaoz - 6 months ago 13
Javascript Question

Looking for a specific word with regular expression in javascript

I've been looking for an answer in SO, but I don't get a straight answer or they're for languages other than JavaScript. I want to use regular expression to look for a class name in a list of classes.

So for example I have this HTML and I want to check if it has the class

hidden
somewhere in the list of classes:

<div class="target box hidden"></div>


I'm using this JS code, but it doesn't work:

// ON CLICK DO THE BELOW:
var divs = document.getElementsByTagName('div'),
re = /\bhidden\b/gi, //here's the regEx
i;

for (i = 0, max = divs.length; i < max; i += 1) {
if (divs.className === 'targets') {
var targets = divs[i];

if (targets.match(re)) {
targets.replace('hidden', '');
} else {
targets.className = 'target box hidden';
}
}
}


Basically, I wanna do a show/hide functionality, i.e. if
hidden
class is present then hide element, otherwise show element.

Many Thanks

Answer
function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,' ');
    }
}

Hope the code can be helpful.