Trim input field value to only alphanumeric characters/separate spaces with . with jQuery
So I'm trying to have an input field where I can enter any characters, but then take the inputted value lowercase it, remove any non alphanumeric characters, leaving "." instead of spaces.
For example, If I enter:
Earth is 70% water, -!*#$^^ & 30% LAnd 开发者_运维技巧 The output should be: earth.is.70.water.30.landAny idea how this can be done without masking with jQuery?
This is not really a jQuery question, it can be done with simple Javascript. First you need to lowercase the text, then replace spaces with periods, then remove non-alphanumeric:
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 multiple spaces as periods, as the user inputted. If you want it to match your answer (which actually condenses multiple spaces into one), then add on an extra replace:
myStr=myStr.replace(/\.+/g, ".");
$(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;
}
});
});
Bind to the keyPress
event and cancel out non alpha numeric chars.
Sample code:
$("#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;
}
});
精彩评论