12

I'm trying to remove the fullstops, commas and spaces from a string. I'm pretty sure I have to do this using this: str.replace(<some Regex here>, "");

I'm just not very familiar with Regex, how can I accomplish this?

0

3 Answers 3

30

Use this regex /[.,\s]/g

var str = 'abc abc a, .aa ';

var regex = /[.,\s]/g;

var result = str.replace(regex, '');

console.log(result);

You don't need to escape character except ^-]\ in character class []

Any character except ^-]\ add that character to the possible matches for the character class.

Sign up to request clarification or add additional context in comments.

4 Comments

You don't need the backslash before the . in the brackets unless you're escaping the ] since the matches are literal.
Ah. Amending my comment above to include that it is also necessary to escape backspace itself because it will escape other characters. Cheers.
Sorry I meant backslash \. Pretty tired right now. Not directly relevant to the question, but meant in general in case for future readers since my above comment is only partially correct.
I was attempting to clarify that this is another exception that needed escaping in addition to ] and ^ within regex square brackets if trying to literally match those characters. Maybe a few others I missed. Not relevant to the question or answer; just correcting my above comment.
7

I believe this should do it:

str.replace(/[.,\s]/g, '');

Comments

-3

Something like this should work...

str=str.replace(/./g,'').replace(/,/g,'').replace(/ /g,'');

Comments

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.