How to remove ZIP code and country from a string

Asked

Viewed 49 times

-1

I’m using Javascript to manipulate some strings that comes from an API and I need to remove the zip code and country from one of these strings.

Basically, I get the phrase like this:

"R. Anderson Ferreira dos Réis, 122 - Conj. Hab. Joel Marques, Tauá - CE, 63660-000, Brasil"

And I need to make arrangements to get rid of the zip code and the country, like this:

"R. Anderson Ferreira dos Réis, 122 - Conj. Hab. Joel Marques, Tauá - CE"

I know it is possible to use the replace() method for this, but the regex I used didn’t work. I tried something like this to get Cpf off:

let text = "R. Anderson Ferreira dos Réis, 122 - Conj. Hab. Joel Marques, Tauá - CE, 63660-000, Brasil"

const result = text.replace(/\d\d((\d\d\d)|(\.\d\d\d-))\d\d\d, '')

But that code doesn’t work.

Someone would know how to do it the right way?

  • I believe in the title of your question is ZIP code instead of CPF, right?

2 answers

1


The expression below looks for 5 numbers in the sequence, a dash, 3 more numbers in the sequence and then everything in front. It may help but depending on the variation of your inputs you may need to adjust the expression.

const input = 'R. Anderson Ferreira dos Réis, 122 - Conj. Hab. Joel Marques, Tauá - CE, 63660-000, Brasil';

console.log(
   input.replace(
     /((,\s)?\d{5}-\d{3}.*)/g,
     ''
   )
);

1

You can solve it in a very simple way, I don’t know if the most correct one would be something like this:

var texto = "R. Anderson Ferreira dos Réis, 122 - Conj. Hab. Joel Marques, Tauá - CE, 63660-000, Brasil"

var objeto = texto.split(',')

Would have his string separated by , on an object and discard the ones you don’t need through the indices, then you can just concatenate the indices.

Browser other questions tagged

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