How to format a value in Javascript?

Asked

Viewed 2,315 times

8

What is the simplest way to format the value 1234213412341 for 1234.2134.1234-1 using Javascript?

<script>
    function formatar_valor(strvalor){
        var formatado;
        // formata
        return formatado
    }
    alert(formatar_valor('1234213412341'));
</script>

4 answers

9


Although there are other ways I think the best is to go in the simplest and insert the formatting characters in the appropriate locations.

function formatar_valor(strvalor) {
    return strvalor.substring(0, 4) + "." + strvalor.substring(4, 8) + "." + 
             strvalor.substring(8, 12) + "-" + strvalor.substring(12, 13);
}
console.log(formatar_valor('1234213412341'));

I put in the Github for future reference.

7

You can do it with a cycle for, despite the fact that the @Maniero solution is the simplest:

function formatar(str) {
    str = str.split('');    // converter em array
    var pedacos = [];    
    var ultimo = str.pop(); // guardar o ultimo numero
    for (var i = 0; i < str.length; i = i + 4){
        pedacos.push(str.slice(i, i + 4).join('')); // juntar pedacos de 4 caracteres
    }
    pedacos = pedacos.join('.'); // juntar pedacos com pontos na união
    pedacos = pedacos.concat('-', ultimo); // juntar "-" e o ultimo numero
    return pedacos;
}
var novaString = formatar('1234213412341');
alert(novaString);

jsFiddle: https://jsfiddle.net/n4nybas4/

7

If you want something generic, in which masks can be applied to various patterns

<script>
function format(mask, number) {
   var s = ''+number, r = '';
   for (var im=0, is = 0; im<mask.length && is<s.length; im++) {
     r += mask.charAt(im)=='X' ? s.charAt(is++) : mask.charAt(im);
   }
   return r;
}    

console.log(format('XXXX.XXXX.XXXX-X', 1234213412341)); // esse primeiro é o que vc quer
console.log(format('XX/XX/XX/XX/XX/XX,X', 1234213412341));
console.log(format('XX muito XX manero XX.XX.XX.XX.X', 1234213412341));
</script> 

source: https://stackoverflow.com/a/14231497/1685571

6

An alternative solution to deal with the problem:

function formatar_valor(str) {
    var split = str.match(/.{1,4}/g),          // divide a string em blocos de 4
        join  = split.join('.');               // junta os blocos colando-os com um .

    return join.replace(/\.(?!.*?\.)/, '-');   // substitui o ultimo . por um -
}

alert(formatar_valor('1234213412341'));        // devolve: 1234.2134.1234-1

See example in Jsfiddle.


function formatar_valor(str) {
    var split = str.match(/.{1,4}/g),
        join  = split.join('.');
    
    return join.replace(/\.(?!.*?\.)/, '-');
}

alert(formatar_valor('1234213412341'));

  • @And I love the system so much camelCase. :)

  • I also prefer :p only edited on account of the name I was calling on Alert, if it is wrong can reverse the edition.

  • @You did well, leave it at that!

Browser other questions tagged

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