Create mask for a text [duplicate]

0

I need to return a value of CNPJ with a mask through Javascript for a text in a td tag of my html code. The value is returned from the default bd of CNPJ as in the code below:

<tr th:each="cliente : ${clientes}" class="cliente">
<td id="#cnpj" th:text="${cliente.cnpj}" class="cnpjTd"></td>
<td id="#razaosocial" th:text="${cliente.razaoSocial}"></td>

For example, the cnpj client returns a value of "11111111111111" and needs to be formatted as "1111111111 / 1111-11."

How can I do this?

    
asked by anonymous 22.02.2018 / 14:45

1 answer

0

I have a code here that I always use and saves me a lot .. It follows below, you just call the function with the value you want.

  $(document).ready(function(){
    $("#mascarar").click(function(){
      $("#depois").html(Mascara($('#antes').html()));
    });
  });
  function Mascara(valorFormatar) {
    //Coloca ponto entre o segundo e o terceiro dígitos
    valorFormatar=valorFormatar.replace(/^(\d{2})(\d)/,"$1.$2")

    //Coloca ponto entre o quinto e o sexto dígitos
    valorFormatar=valorFormatar.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")

    //Coloca uma barra entre o oitavo e o nono dígitos
    valorFormatar=valorFormatar.replace(/\.(\d{3})(\d)/,".$1/$2")

    //Coloca um hífen depois do bloco de quatro dígitos
    valorFormatar=valorFormatar.replace(/(\d{4})(\d)/,"$1-$2")

    return valorFormatar;
  }
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head><body><h2>Dadoantes</h2><pid="antes">09673442000173</p>

  <h2>Dado depois</h2>

  <p id="depois"></p>

  <button type="button" id="mascarar">Formatar!</button>
  </body>
</html>
    
22.02.2018 / 15:17