1

I'm looking for a basic regex that removes any space. I want to use it for ZIP code.

Some people insert space after, before or in between the ZIP code.

I'm using /^\d{5}$/ now. I want to expand it to include space removal.

How can this be improved?

1
  • do you use it for verification? Commented Sep 6, 2011 at 21:48

3 Answers 3

3

(I'm considering you want to remove spaces in your string, not verifying if it is valid even with spaces)

You can substitute one or more spaces (globally)

/\s+/g 

by nothing.

zip.replace(/\s+/g, ""); 

Example in my browser's JS console:

> " 02 1 3 4".replace(/\s+/g, ""); "02134" 
Sign up to request clarification or add additional context in comments.

1 Comment

It depends on your design flow. If you want to first remove the spaces and then verify it, apply what I demonstrated here and then use your current regex to see if the input is valid. Now if you want to combine the approaches, verifying if it's valid even with spaces all at once, use @Jacob Eggers' answer.
3

Here's a regex you can use instead of your current one to ignore any and all spaces.

/^(\s*\d){5}\s*$/ 

2 Comments

@Mohsen: It certainly works, try if (" 123 45 ".match(/^(\s*\d){5}\s*$/)) console.log("yes");
this will tell you if you have 5 digits, but won't trim the spaces - isn't that what OP wants?
0

If you're sanitizing a form input or something, it's probably easiest to use:

zip = zip.replace(/\D/g,'');

you can then validate without a regex, just use the .length property on String.

if(zip.length != 5) alert('failed!');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.