Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript convert string to safe class name for css

Tags:

I am sure this must of been asked before but can't find any in the search. What is the fastest way to ensure all non safe characters are removed from a string allowing it to be used in a CSS class name?

like image 784
John Magnolia Avatar asked Oct 02 '11 14:10

John Magnolia


People also ask

Can we change class name in JavaScript?

The document. getElementById() method is used to return the element in the document with the “id” attribute and the “className” attribute can be used to change/append the class of the element.

How to handle strings in JavaScript?

To join together strings in JavaScript you can use a different type of string, called a template literal. You can use the same technique to join together two variables: const one = "Hello, "; const two = "how are you?"; const joined = `${one}${two}`; console. log(joined); // "Hello, how are you?"

How do you set a class as an element?

To change all classes for an element:getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)

How would you convert a value to a string in JavaScript?

Converting Values to Strings Values can be explicitly converted to strings by calling either String() or n. toString() . With the String() function, let's convert a Boolean value to a string by passing the value true into the parameters for String() .


1 Answers

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")); 
like image 158
PleaseStand Avatar answered Feb 09 '23 17:02

PleaseStand