Javascript help needed

Soldato
Joined
1 May 2003
Posts
3,207
Location
Bucks
Hi,

I am pretty new to Javascript and wondered if someone here might be able to help....

I need to strip out all illegal characters from a text string entered into an input box. Currently the illegal chars we want to remove are hardcoded, but I want to change it so we specify which characters are allowed: A - Z. 0 - 9. This way we won't need to hardcode every possible illegal char possible!

Here is my current code for removing commas and full stops from a text string 'val_txt_list':

Code:
for(i=0; i<val_txt_list.length; i++){
if(val_txt_list.indexOf(",") > -1){
   val_txt_list=val_txt_list.replace(",","")
}
if(val_txt_list.indexOf(".") > -1){
   val_txt_list=val_txt_list.replace(".","")
}
}

I have spent a long time searching the net for what I would have thought would be a well practiced method but haven't found anything good yet.

Any help greatly appreciated :)
 
The best way to do this would be regular expressions (regex for short). There's a primer here:

http://www.regular-expressions.info/

And info on how to do regular expressions using JavaScript here:

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

You'd probably want do run a "Match" on the whole string and only submit if the whole string successfully matches.

Also don't forget that anything done at the client side (JavaScript) could be falsified, you can never really trust anything that comes back from JavaScript. Thus if it's important you should also double check server side.
 
Last edited:
Thanks! A search through some regex examples found me this one using 'Replace':

Code:
temp =  temp.replace(/[^a-zA-Z 0-9]+/g,'');

Works great and no more looping through each character in the string.

Cheers :)
 
Back
Top Bottom