Clear CEP with JavaScript


How to clear the formatting of a zip code field in this format: 87.678-000 ?

I need to remove the "." and the "-" and return only the numbers. I tried something like this, unfortunately it didn't work.

var i = '^[0-9]+$';
var reg = new RegExp(i);


If all you want is to remove the dashes and dots…

var str = str.replace("-", "").replace(".", "");

Where str is the string with the zip code.

If you want to see if a string is a valid zip code, you can use something like:

// força bruta não, força brutíssima! // após 3 edições, já não tão bruta...
var regexp = /\d\d((\d\d\d)|(\.\d\d\d-))\d\d\d/;
var match = str.match(regexp);

Then you check if there was a match (if match is null, the string is not a valid zip code). This regular expression will take both formatted and unformatted zip codes.

PS: I'm not considering whether CEP's with leading zeros are valid, because I don't know the CEP formation rules.

Edit: I tweaked the code to make it less rough.

Scroll to Top