javascript convert string to safe class name for css

I use this for my selectors, IDs or classes names:

String.prototype.safeCSSId = function() {
  return encodeURIComponent(this)
    .toLowerCase()
    .replace(/\.|%[0-9a-z]{2}/gi, '');
}

console.log("The dæmon is in the detail.".safeCSSId());

I would replace anything that is not a lowercase letter or digit, and then I would add a special prefix to avoid collisions with class names you have used for other purposes. For example, here is one possible way:

function makeSafeForCSS(name) {
    return name.replace(/[^a-z0-9]/g, function(s) {
        var c = s.charCodeAt(0);
        if (c == 32) return '-';
        if (c >= 65 && c <= 90) return '_' + s.toLowerCase();
        return '__' + ('000' + c.toString(16)).slice(-4);
    });
}

// shows "prefix_c_a_p_s-numb3rs-__0024ymbols"
alert("prefix" + makeSafeForCSS("CAPS numb3rs $ymbols"));

You can try the urlify.js from django.

Get it from: https://github.com/django/django/blob/master/django/contrib/admin/static/admin/js/urlify.js


If you mean the following symbols

!"#$%&'()*+,./:;<=>?@[\]^`{|}~

then just replace them with nothing:

names = names.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g, '');

(I may have added an extra, or not enough, escape characters in there)

Here is a quick demo.

But just so you know, not all of those symbols are "unsafe", you could just escape the symbol when targeting the class name (ref).