I am creating a JavaScript function that will take a user inputted value and and create a CSS class name out of it. The following expression can be used to detect whether the end result follows valid css rules
-?[_a-zA-Z]+[_a-zA-Z0-9-]*
but I need to find a way to use it to remove all invalid characters.
I was thinking of something like:
var newClass = userInput.replace(EVERYTHING BUT /[_a-zA-Z0-9-]/, "");
A very small modification to your existing regex should work, using the
^operator andg:Which should be used as:
The
^character, as the first character inside the brackets[], specifies to match what’s not in the brackets (i.e. – the characters you want to strip).The
gmodifier performs a global-match on the entire input string.