Snippet: JavaScript: Create css class/id/name identifier cleanly from string

Snippet: JavaScript: Create css class/id/name identifier cleanly from string

Based on
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_html_id/7
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_clean_css_identifier/7
this simple JavaScript snippets turns strings into valid HTML id / class / name identifiers (http://www.w3.org/TR/html4/types.html#type-name)

Code:

  1. clean_css_identifier = function(id) {
  2.     id = id.toLowerCase();
  3.     id = id.replace(" ", "-").replace("_", "-").replace("[", "-").replace("]", "-");
  4.  
  5.     // As defined in <a href="http://www.w3.org/TR/html4/types.html#type-name" title="http://www.w3.org/TR/html4/types.html#type-name">http://www.w3.org/TR/html4/types.html#type-name</a>, HTML IDs can
  6.     // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
  7.     // colons (":"), and periods ("."). We strip out any character not in that
  8.     // list. Note that the CSS spec doesn't allow colons or periods in identifiers
  9.     // (<a href="http://www.w3.org/TR/CSS21/syndata.html#characters" title="http://www.w3.org/TR/CSS21/syndata.html#characters">http://www.w3.org/TR/CSS21/syndata.html#characters</a>), so we strip those two
  10.     // characters as well.
  11.     id = id.replace(/[^A-Za-z0-9\-_]+/gi, '', id);
  12.  
  13.     // Removing multiple consecutive hyphens.
  14.     id = id.replace(/\-+/gi, '-', id);
  15.  
  16.     return id;
  17.   };

Examples:

  1. clean_css_identifier('aaa'); // Returns "aaa"
  2. clean_css_identifier('AAA'); // Returns "aaa"
  3. clean_css_identifier('A A A'); // Returns "a-a-a"
  4. clean_css_identifier('aA a123'); // Returns "aa-a123"
  5. clean_css_identifier('a!"§$%&/(a'); // Returns "a-a"

This is just a first quick solution which could easily be extended and be optimized. I'll perhaps do that whenever I'll find the time :)

So leave a comment if you found or created a better solution.

Kommentare

Kommentar hinzufügen

Der Inhalt dieses Feldes wird nicht öffentlich zugänglich angezeigt.

Weitere Informationen über Formatierungsoptionen