Skip to content

Instantly share code, notes, and snippets.

@m4olivei
Forked from wesruv/function.js
Last active October 31, 2016 18:17
Show Gist options
  • Save m4olivei/75b88acd2c647d21f37d42396c468ddc to your computer and use it in GitHub Desktop.
Save m4olivei/75b88acd2c647d21f37d42396c468ddc to your computer and use it in GitHub Desktop.
Clean CSS identifier from string
// In a perfect world, you'd never have to do this. Wish I lived in a perfect world.
/**
* Convert a string to a usable class name
* @param {string} stringToConvert String of text
* @return {string} Usable class name
*/
function convertStringToClassName(stringToConvert) {
if (typeof stringToConvert === 'string') {
return stringToConvert.trim().replace(/[\s-_]+/g, '-').replace(/[^\w-]|^-|-$/g, '').replace(/-+(?=-)/, '').toLowerCase();
}
};
@m4olivei
Copy link
Author

@wesruv this will also remove leading and trailing "-"'s and remove consecutive dashes, which may have been left after the second replace removes a sequence of all non-word characters between two dashes, such as an input like:

convertStringToClassName('-this-shit-crazy-!!!!-right-')

@wesruv
Copy link

wesruv commented Oct 31, 2016

nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment