Alex Rivera | Logout

Regex - Remove everything from a string that does not match an expression

Asked 2012-08-03T19:52:01.210
22

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-]/, "");
Edit
Report

1 Answer

2

var result = userInput.replace(/[^\w-]/g, '');

answered 2012-08-03T19:58:58.427

Your Answer