Replace Javascript (How It Works?)

Asked

Viewed 630 times

3

Is there any way anyone could explain to me how Replace works? I’m trying to count the number of characters typed by a user in the zip code, but it is with Mascara, and then the blank fields are with _ (Underline). I tried to do so to remove the trace and it worked, but keeps counting the _

var zipCodeValue = $(ZipCode).val();
zipCodeValue = zipCodeValue.replace("-","")

in this code above it removes the dash, but counts the whitespace with underline, so I tried to do so:

zipCodeValue = zipCodeValue.replace("-","").replace("_","");

But it only removes 1 Underline. I also tried to do using the same variable that I saw in this example below, but I did not understand how it is written, I searched in several forums and also in several youtube videos, but it does not show the functionality. could someone please explain to me how this type of Replace??? variable works and how it works. / \ | g the only thing I think I’m right on would be \ which I understand to be for reserved characters.

var er = /\^|~|\?|,|\*|\.|\-/g;

if you notice the image below, - is removed and 1 _ also. inserir a descrição da imagem aqui

  • Are using some plugin ?

  • I’m using inputmask to make the mask

1 answer

4


You can use a regex:

zipCodeValue = zipCodeValue.replace(/[\-_]/g,"");

anything that is dash or underline it will remove.

The bars define the beginning and the end of the regex, the brackets define a set of elements that in this case are being represented by \- (dash)* and _ (underline), the g after the end of the regex means (global), i.e..

* The backslash before the dash serves to escape it, for in a regex it is a special character.

Read more here: Regexp

  • Thanks Junior, gave right here :) Tks

Browser other questions tagged

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