Regular Expression for RG

8

I have a% w / o of% that defines the points by the maximum number of digits.

Expression:

function Rg(v){
    v=v.replace(/\D/g,"");
    if(v.length == 9) v=v.replace(/(\d{2})(\d{3})(\d{3})(\d{1})$/,"$1.$2.$3-$4");
    return v
}

expressão regular RG :

But I would like an expression that standardizes with different digits. Example:

88.888.888-8 RG :

Without using another 8.888.888-8 as the following example:

function Rg(v){
    v=v.replace(/\D/g,"");
    if(v.length == 9) v=v.replace(/(\d{2})(\d{3})(\d{3})(\d{1})$/,"$1.$2.$3-$4");
    if(v.length == 8) v=v.replace(/(\d{1})(\d{3})(\d{3})(\d{1})$/,"$1.$2.$3-$4"); 
    return v
}

Is it possible?

    
asked by anonymous 25.06.2014 / 15:45

2 answers

10

Friend, here it is, do not forget to consider who helps you instead of asking other questions and forget the answers. Help the whole community! ;)

function Rg(v){
    v=v.replace(/\D/g,""); //Substituí o que não é dígito por "", /g é [Global][1]
    v=v.replace(/(\d{1,2})(\d{3})(\d{3})(\d{1})$/,"$1.$2.$3-$4"); 
    // \d{1,2} = Separa 1 grupo de 1 ou 2 carac. (\d{3}) = Separa 1 grupo de 3 carac. (\d{1}) = Separa o grupo de 1 carac.
    // "$1.$2.$3-$4" = recupera os grupos e adiciona "." após cada.

        return v
    }

Example with MSDN Link function:

function styleHyphenFormat(propertyName)
{
  function upperToHyphenLower(match)
  {
    return '-' + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
    
25.06.2014 / 15:51
0

MORE CORRECT

It was already almost good in @RonnyAmarante's response, but according to comments, forgot the "X" ... As it is not always possible to deal with errors, here includes the parameter errChar only to remember or not with "?" that there is something strange about RG.

function RgFormat(v0,errChar='?'){
    var v = v0.toUpperCase().replace(/[^\dX]/g,'');
    return (v.length==8 || v.length==9)?
       v.replace(/^(\d{1,2})(\d{3})(\d{3})([\dX])$/,'$1.$2.$3-$4'):
       (errChar+v0)
    ;
} 

NOTE: Because you accept 1 or 2-digit start (you could also fill in with zero), ^ is important for completeness in the case of 2 digits.

... Since we are talking about an error message, we have to validate the check digit ( $4 ), see question Validation of RG or this didactic explanation .

    
22.10.2016 / 18:32