Trim input field value for alphanumeric characters / individual spaces only. with jQuery

So, I'm trying to have an input field where I can enter any characters, but then accept the entered value in lower case, delete any non-alphanumeric characters, leaving ".". instead of spaces.

For example, if I enter:
Earth - 70% of the water, -! * # $ ^^ and 30% LAnd

The output should be:
earth.is.70.water.30.land

Any idea how this can be done without disguise using jQuery?

+4
source share
3 answers

This is not a jQuery question, it can be done using simple Javascript. First you need to enter the text in lowercase, then replace the spaces with periods, and then remove the non-alphanumeric characters:

var myStr = "Earth is 70% water, -!*#$^^ & 30% LAnd" myStr=myStr.toLowerCase(); myStr=myStr.replace(/ /g,"."); myStr=myStr.replace(/[^a-zA-Z0-9\.]+/g,""); 

This answer would leave a few spaces as periods as the user entered. If you want it to fit your answer (which actually condenses multiple spaces into one), add an extra replacement:

 myStr=myStr.replace(/\.+/g, "."); 
+12
source
 $(document).ready(function () { $(".ui-widget-content .ui-autocomplete-input").keydown(function (event) { if (event.shiftKey) { return false; } if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 97 && event.keyCode <= 122) || (event.keyCode >= 65 && event.keyCode <= 90)) { return true; } else { return false; } }); }); 
+1
source

Bind keyPress to event and undo alphabetic characters without letters.

Code example:

 $("#target").keypress(function(event) { var key = event.which; var keychar = String.fromCharCode(key).toLowerCase(); // allow control keys if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) return true; if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) == -1)) event.preventDefault(); return false; } }); 
0
source

All Articles