views:

45

answers:

2

Hey everybody,

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

A: 

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.

JamesStuddart
thx, this is the same problem I have. But thanks anyway. ;)
praethorian
I would put it down to how you are implementing it then, as your issue does not happen in the system I have created that uses the above code.
JamesStuddart
+1  A: 

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

Ninja Dude