Replace Javascript (How does it work?)

3

Could someone explain how Replace works? I'm trying to count the number of characters entered by a user in the zip code, but it is with Mascara, and there the blank fields are with _ (Underline). I tried to do so to remove the trace and it worked, but keep counting the _

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

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

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 anyone explain to me how it mounts and works this kind of variable from Replace ??? what is the / \ | g the only thing I think I'm sure would be in \ that I understand is for reserved characters.

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

If you look at the image below, - is removed and 1 _ is also removed.

    
asked by anonymous 16.12.2016 / 22:51

1 answer

4

You can use a regex:

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

Whatever is dashed or underline it will remove.

The bars define the start and end of the regex, the brackets define a set of elements that in this case are represented by \- (trace) * and _ (underline), og after the end of regex means (global), ie it will not stop in the first underline, as was happening earlier.

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

Read more here: RegExp

    
17.12.2016 / 00:16