Reputation: 146
Incredibly simple question, but a combination of beer and football is leaving me hopelessly inadequate! ( bound to be a duplicate too, but I can't for love nor money find it )
I have an element
<div class="inline-block" id="colour">
I would like to check if the class contains bg-anycolour ( ie. bg-red or bg-yellow or bg-blue and so on )
if not add class bg-colour ( again bg-colour could be bg-red or bg-white or bg-pink and so on )
if true replace bg-anycolour with bg-colour
I know I am looking for regex match contains and replace, but not to be constrained by any other classes that might be added at a later date.
function setColour(colour) {
//need to add class br-{colour} but also to remove colour if already there
if ($("#colour").attr("class").match(/(** what goes here **)/))
{
** and replace?? **
}
else
{
$("#colour").addClass('bg-' + colour)
}
Thanks
Upvotes: 1
Views: 156
Reputation: 253318
Given the clarifications in your questions, and the comments, as well as your own posted answer, it seems that the question you're asking is:
how can I find a class-name with the format
bg-<colourName>
and replace that<colourName>
portion with a new, given, colour-name if it exists, and addingbg-colourName
if it doesn't exist?
With that in mind -and I'm curious as to the use-case because it seems unnecessarily complex- I'd suggest the following approach:
function setColour(colour) {
$('#colour').attr('class', function (i, oldClasses) {
return 'undefined' === typeof oldClasses ? 'bg-' + colour : oldClasses.replace(/\b(bg-[a-z]+)\b/i, function (a) {
return 'bg-' + colour;
});
});
}
Representative JS Fiddle demo.
References:
Upvotes: 0
Reputation: 932
//need to add class br-{colour} but also to remove colour if already there
function setColour(colour) {
var ele = $("#colour");
var classname = ele.attr("class") || "";
var classStartIndex = classname.indexOf("bg-");
var classEndIndex = -1;
if (classStartIndex >= 0) {
$.each((classname.substring(classStartIndex, classname.length)).split(""),
function (i, val) {
if (val == " ") {
classEndIndex = i;
return;
}
});
if (classEndIndex == -1)
classEndIndex = classStartIndex.length;
else
classEndIndex = classStartIndex + classEndIndex;
ele.removeClass(classname.substring(classStartIndex, classEndIndex));
}
else {
ele.addClass("bg-" + colour)
}
}
Upvotes: 0
Reputation: 146
Sorted, apologies for the clarity of question.
function setColour(colour) {
//check if class exists that has pattern bg-w+
if ($("#colour").attr("class").match(/bg-\w+/))
{
var str = $("#colour").attr("class");
var regex = /bg-\w+/;
//get match and remove
$("#colour").removeClass(regex.exec(str)[0]);
}
//always add the new class
$("#colour").addClass('bg-' + colour);
};
Upvotes: 1