$('.s').keyup(function(e) {
if (!/[A-Za-z0-9]/.test(String.fromCharCode(e.which))) {
return false;
}
I wonder what is the best regex solution for my application.
I have an ajax-based search that should just trigger the search when actual characters are pressed like a-Z (upper and lowercase), numbers and maybe a questionmark, a dash(hyphen), and an exclamation mark. Also the spacebar should be enabled.
Otherwise the ajax search would be triggered as well if the shift-, option, or control-key, is pressed.
What’s the easiest regex pattern to understand here?
thank you for your help
The basic form of your regex seems fine, just include what you want to include, and be aware of accented characters. Alternately, you might exclude the characters you don’t want.
But I’d use the
keypressevent rather thankeyupevent for this.keypressfires when an actual typeable character is typed, and fires on key repeat (whereas you only get onekeyupeven if a key repeats).Update: This isn’t necessarily true cross-browser (sigh), see the update below.keypressis not fired for Shift, Meta, Ctrl, etc.If you’re hookingI’d also probably include a brief delay so as to avoid lots of unnecessary searches. If the person fairly rapidly types “fred” there’s no need to search on “f”, “fr”, and “fre”.keypress, I probably wouldn’t filter anything out (no need for the regex), because I’d rather defer to the browser and its awareness of locale for what consitutes a real character.Here’s an example of what I mean (combining
keypresswith a slight delay). If you really want to filter out certain chars, you can do that in the event handler, but I haven’t below for the reasons above:HTML:
JavaScript (using jQuery, since you tagged your question with
jquery):Live copy
That example searches a quarter second after the last
keypressit sees; adjust the parameter tosetTimeoutas you see fit.Update: After your comment below about arrow keys, I thought “but you don’t see arrow keys on
keypress, do you?” and the answer is: You do on Opera and a couple of others. sigh So yes, with a filter:Live copy (this one just filters out the arrow keys; you’ll want to extend that)
If you don’t already know if it, this page is great for information around the madness that is keyboard events across browsers. It may be slightly dated.