Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - How do I exclude "%" and "_"?

Im allowing numbers, letters, and special characters except for % and _ in my html textbox. I have the pattern /[a-zA-Z0-9!@#$^&*()-+=]/. I think its not the best way to do it because I have to list all special characters except the two mentioned. Is there a way in which I don't have to list all special characters and don't include the two mentioned? BTW, Im using javascript regex.

For the demo please see http://jsfiddle.net/ce8Th/

Please help.

like image 361
NinjaBoy Avatar asked Jan 14 '13 01:01

NinjaBoy


People also ask

What does _ do in regex?

The _ (underscore) character in the regular expression means that the zone name must have an underscore immediately following the alphanumeric string matched by the preceding brackets. The . (period) matches any character (a wildcard).

How do you stop special characters in regex?

Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .


1 Answers

There's no need for that complex loop. Just call replace directly on the whole string:

$(this).val(function (i, v) {
    return v.replace(/%|_/g, '');
});

Here's your fiddle: http://jsfiddle.net/ce8Th/1/

like image 148
Joseph Silber Avatar answered Oct 03 '22 15:10

Joseph Silber