replacing chars using jQuery
I am trying to replace all special characters except alphanumerics using js.
function checkWholeString(string,len){
if(string != null && string != ""){
var regExp = /^[A-Za-z0-9-]+$/;
for(var i=0; i < string.length; i++){
var ap = string.charAt(i);
if(!ap.match(regExp)){
string = string.replace(ap," ");
}
}
开发者_开发知识库 return jQuery.trim(string);
}
}
trouble is when I am holding for example "a" key pressed and while I am still holding it I will press another key it will add blank spaces to the text.
Is there any chance to improve the code to get rid of this? Any help would be most welcome.
Thanks Pete
try something like:
function onkeyup(event,directoryName) {
return directoryName.replace(/([.?*+^$[\]!\\/\'@\"(){}-])/g, "");
}
this is what I have used in the passed on several projects to remove the special chars.
1) using .blur()
event
$(function() {
$('textarea').bind('blur', function() {
var val = $(this).val().replace(/[^A-Za-z0-9- ]/g,' ')
val = val.replace(/^\s+|\s$/g,'');
$(this).val( val );
});
});
Test this code http://jsbin.com/ebene4
2) using .keypress()
.keyup()
events
$(function() {
$('textarea').bind('keyup keypress', function() {
var input = $(this).val() ;
//replace special chars in the input string with a blank space
input = input.replace(/[^A-Za-z0-9- ]/g,' ');
$(this).val(input);
}).bind('blur', function() {
$(this).val( $.trim($(this).val()) );
});
});
you can try it here http://jsbin.com/amera3
PS : replacing chars with an empty string is better than replacing with a blank space
精彩评论