1

I am trying to remove all special characters except punctuation from a customer complaint textarea using this code:

var tmp = complaint;
complaint = new RegExp(tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, ''));

but it keeps placing "/" in front, and in back of the string after sanitizing.

Example:

 Hi, I h@ve a% probl&em wit#h (one) of your products.

Comes out like this

 /Hi, I have a problem with one of your products./

I want

 Hi, I have a problem with one of your products.

Thanks in advance for any help given.

1
  • 1
    you replace which results in a string...then using that string you create a regexp object...no need to make a regexp object though Commented Sep 12, 2013 at 0:15

2 Answers 2

1

The variable complaint is converted to a regular expression because you use the RegExp() constructor.

This probably isn't what you want. (I assume you want complaint to be a string).

Strings and regular expressions are two completely different data types.

Your output demonstrates how JavaScript displays regular expressions (surrounded by / characters).

If you want a string, don't create a regular expression (i.e. remove the RegExp constructor).

In other words:

complaint = complaint.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');
0
1

You don't need the RegExp constructor:

complaint = tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');
3
  • 1
    Doesn't even need a temp variable, complaint = complaint.replace(...)
    – elclanrs
    Commented Sep 12, 2013 at 0:14
  • @JeffWalters: you won't just clean up your Code, it's the Remedy to your Problem, See jahroy's answer.
    – collapsar
    Commented Sep 12, 2013 at 0:16
  • Yes. It did. Thank you so much. I was banging my head trying to figure this one out. Now I know for future use. Commented Sep 12, 2013 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.