Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing all characters in the String that are not letters or numbers 1

Status
Not open for further replies.

vasilek

Programmer
Jan 5, 2003
99
US
Hi. I never know what text the user will type in so it will be safe to remove all the charachters in the String that are not letters or numbers. For example:

"Mother's Day" I would like to become "MothersDay"

"Thank You" > "ThankYou"

"St. Patrick's Day" > "StPatrick'sDay"

"Red/Blue Car" > "RedBlueCar"

"Red, Blue Car" > "RedBlueCar"

"December 28, 2004" > "December282004"

Does it make sence? Is it possible? Thank you.
 
just use this function and you'll be set:
Code:
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript>
function regexpCheck(str) {
   str = str.replace(/[^a-zA-Z0-9]/g, "");
   alert(str);
   blahForm.blahText.value = '';
   blahForm.blahText.focus();
}
</SCRIPT>
<BODY>
<FORM NAME="blahForm">
<INPUT TYPE=TEXT NAME=blahText><br>
<INPUT TYPE=BUTTON VALUE='remove alphanumeric' NAME=blahButton ONCLICK='javascript:regexpCheck(blahForm.blahText.value);'>
</FORM>
</BODY>
</HTML>

-kaht

banghead.gif
 
You may use the replace function of the String object like this:
Code:
[COLOR=blue]function[/color] RemoveExtraChars(text)
{
  [COLOR=green]// This Reg Expression will match any
  // char that's not a letter or number[/color]
  regEx = [COLOR=blue]new[/color] RegExp("[^a-zA-Z0-9]", "g");
  [COLOR=green]// This replaces the regular expression
  // match with an empty string...[/color]
  newText = text.replace(regEx, "");
  [COLOR=blue]return[/color] newText;
}

The "g" in the constructor of the RegExp object makes the match occur for the whole string. Ommitting the "g" will cause only the first match to be replaced.

If you don't know about Regular Expressions, you can read a little bit about them at:

Hope this helps!

JC


We don't see things as they are; we see them as we are. - Anais Nin
 
Hey kaht, I guess you beat me to it! :)

JC

We don't see things as they are; we see them as we are. - Anais Nin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top