Based on
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_h…
https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_c…
this simple JavaScript snippets turns strings into valid HTML id / class / name identifiers (http://www.w3.org/TR/html4/types.html#type-name)
Code:
clean_css_identifier = function(id) {
id = id.toLowerCase();
id = id.replace(" ", "-").replace("_", "-").replace("[", "-").replace("]", "-");
// As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
// only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
// colons (":"), and periods ("."). We strip out any character not in that
// list. Note that the CSS spec doesn't allow colons or periods in identifiers
// (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
// characters as well.
id = id.replace(/[^A-Za-z0-9\-_]+/gi, '', id);
// Removing multiple consecutive hyphens.
id = id.replace(/\-+/gi, '-', id);
return id;
};
Examples:
clean_css_identifier('aaa'); // Returns "aaa"
clean_css_identifier('AAA'); // Returns "aaa"
clean_css_identifier('A A A'); // Returns "a-a-a"
clean_css_identifier('aA a123'); // Returns "aa-a123"
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.