Applying Jquery mask in value and not input

Asked

Viewed 582 times

0

Hello, I have the following phone and mobile values respectively:

Telephone: 1111111111 Cellular: 11111111111

I already have the value in the database, I would like to present these values formatted with the following masks:

Telephone = (11) 1111-1111 Cellular = (11) 11111-1111

Could someone help me ? I would just apply the masks via Javascript do not want to put in the input, because I save the value only numeric in BD, I would just like to present it formatted.

If anyone can help, thank you!

  • You can use subtring

  • I edited my answer, for lack of attention I answered about formatting in an input, but I’ve arranged for your case, take a look there! If you can mark it as a correct answer, thank you ;)

  • An example of how to format any type of pattern flexibly with a single function: https://answall.com/a/55235/4793

  • Bruno, thank you, but I used our friend’s solution below. Still thank you!

1 answer

2


Use Regex and replace():

function mascaraTelefone(value){
    value = value.replace(/\D/g,"");                  //Remove tudo o que não é dígito
    value = value.replace(/^(\d{2})(\d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    value = value.replace(/(\d)(\d{4})$/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    value = value.substr(0, 15);
    return value;
}

Call the function by passing the value (phone) the return of it will be the formatted phone:

//Esse seria o telefone que vem do banco de dados
var tel = "1125346283"

//Essa variavel você pode apresentar
var telFormatado = mascaraTelefone(tel);
  • 1

    Thank you Lucas! It worked correctly!

Browser other questions tagged

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