View Full Version : help with reg exp

05-04-2004, 02:39 PM
I have a function that should replace the specified characters with an empty string, but it doesn't work. Here is the function

function removeSpecials( strValue )
{ var objRegExp = (/(" ")|("/")|("%")|("*")|("'")|(""")/)
//replace all matches with empty strings
return strValue.replace(objRegExp,'');

the error is an Expected ')'. All help is appreciated, thanks.

05-04-2004, 03:57 PM
function removeSpecials ( strValue ) {
//replace all matches with empty strings
return strValue.replace(/\s\/%\*'"/g,'');

Try that. The problem was you weren't actually making a regular expression, and you were defining the replacement expression with strings. This now reads, "give me the value I passed in, with the following replaced by nothing: whitespace, slash, percent sign, asterisk, apostrophe, or quote -- and look at the whole thing before you quit, to make sure you've replaced them all."

If you're only looking for alphanumeric characters, use this instead:
return strValue.replace(/\W/g, '');
Any non-word character will be replaced.

Be sure to check the FAQ in this forum to find liorean's RegEx tutorials. Read them and love them.

05-04-2004, 04:56 PM
thanks for your help and I will read the tut shortly. I've tried the suggested function above and in my example it did not work. Here is my example

<script language="javascript">
function removeSpecials(strValue) {
//replace all matches with empty strings
return strValue.replace(/\s\/%\*'"/g,'');

function alertme()
var val;
val = removeSpecials(document.form1.example.value)

<form name=form1>
<tr><td><input type=text name="example"><input type=button onclick="alertme()" value="check"></td></tr>

if I am using it wrong please point that out. Could there be a problem with which javascript version I am calling? All help is appreciated, thanks.

05-04-2004, 06:42 PM
Sorry about that - I forgot to group the characters. Use this in place of what it resembles:

return strValue.replace(/[\s\/%\*'"]/g,'');

Notice that there are now brackets surrounding all those characters, which means "find any of these."

Edit: also, if you're not specifically limiting those characters and may care about semicolons, ampersands, and other non-word characters, I just tested with the expression /\W/g and it works just the same -- it happens to strip out all non-alphanumerics.

05-04-2004, 10:30 PM
Thanks a lot, I need to get tight with my reg expressions. :thumbsup:

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum