Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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-]/, "");
like image 936
MindWire Avatar asked Aug 03 '12 19:08

MindWire


People also ask

What does '$' mean in regex?

$ 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.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.

How do I not match a character in regex?

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.

What does regex 0 * 1 * 0 * 1 * Mean?

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.


1 Answers

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.

like image 115
newfurniturey Avatar answered Sep 30 '22 20:09

newfurniturey