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-]/, "");
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
There's two ways to say "don't match": character ranges, and zero-width negative lookahead/lookbehind. Also, a correction for you: * , ? and + do not actually match anything. They are repetition operators, and always follow a matching operator.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
A very small modification to your existing regex should work, using the ^
operator and g
:
/[^a-zA-Z0-9_-]+/g
Which should be used as:
var newClass = userInput.replace(/[^a-zA-Z0-9-_]/g, '');
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 g
modifier performs a global-match on the entire input string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With