Clear ZIP code with Javascript

Asked

Viewed 7,149 times

10

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

I need to take out the "." and the "-" and return only the numbers. I tried something like, unfortunately it didn’t work.

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

3 answers

16

If all you want is to remove the strokes 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 match (if match is null, the string is not a valid ZIP code). This regular expression will take both formatted and unformatted ZIP.

P.S.: I am disregarding whether left zeroes are valid, as I do not know the rules of CEP formation.

Editing: I tweaked the code to make it less gross.

  • 4

    I liked the comment: "brute force no, brute force!" kkkkkk +1 by the reply and comment

  • 1

    tou with @Tafarelchicotti, the comment is anything eheh

  • 1

    It worked out, buddy, thanks!

  • Renan, taking your tip, I have another similar problem. I have a string like this: str = "000.000.000". Which are values, how do I replace the digits, plus leaving the dots "." ?

  • @user7605 Create another question with this question. Then more people will see, and you will have more space to detail the question ;)

  • Okay, I’m creating

Show 1 more comment

7


An alternative solution presented by @Renan is to use this regular expression /\.|\-/ to remove the characters . and - string:

var cep = '87.678-000';
cep = cep.replace(/\.|\-/g, '');

alert(cep); // 87678000

Where the modifier /g is used to search for one or more occurrences where . and - is found, of global use.

Demo


To verify that a CEP is valid(in the format provided by you) could be used something like this:

var cep = '87.678-000';
if (/\d{2}\.\d{3}\-\d{3}/.test(cep))
    alert('Cep é válido!');
else
    alert('Cep inválido!');

Demo

1

I would like to complement the answer by @Renan with a true CEP validation.

Although the Brazilian CEP is not defined by an algorithm itself but only one structured decimal representation of the country, like any logical structure it follows a standard Valizable by Regular Expressions.

Note that I wrote Regular Expressions, plural, as we have 26 States + one Federal District which, in one structure, result in 27 different patterns.

Years ago, when I was researching for CEP-based auto-fill alternatives, at a "time" when there weren’t many Webservices available and/or trusted, I ended up finding the database itself used by Correios for download in a blog that today no longer exists.

The important thing is that amid the article’s comments there was one of none other than Aurélio Marinho Jargas, author of the best reference book for Regular Expressions in Portuguese.

And in this particular comment he published these 27 Regular Expressions which I quickly tried to implement in PHP. Easy, easy, easy...

Despite the relative difficulty I had in porting the code to Javascript, I did, and leave it as a reference to the community in Jsfiddle.

After the basic length check, first the state is checked by a separate Regular Expression. Only then do we test the first five digits of the zip code, which are the ones that matter against the Regular Expression of the informed State.

All credit goes to Master Aurelius, I just packed everything up like a good Padawan. ^_^

  • Note that you start by taking out of the string all non-numeric characters (the call to replace). Thus, ab60125-asd1t50 would be a valid ZIP code. Anyways +1 for being complete and accurate.

  • Thank you for the recognition. As for the point raised, in fact, 60125-150 is rather a valid zip code, but there in Fortaleza / CE. That is why the validation also takes into account the State. If this string was given as input to another State, it would fail.

  • My point is that 60125-150 is a valid zip code, but aaaa6z\alfhkw012sljghwh5sadfslhfw-fwl1çskgnlhsghw5slkdf0 not. The numbers are the same, but the strings are different. I guarantee a postman would throw his card in the trash with a zip code like the second :D

  • In a real setting, for sure. If a mail was received by Post with an invalid zip code, it would be marked with something like "return to sender" or "insufficient address". But anyway, this filtering between well-filled and poorly filled correspondence is a kind of validation. Not that the Post Office has someone to look for numbers in the middle of a text to guess the destination, but in any case...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.