How to format a value in JavaScript?

8

What is the simplest way to format 1234213412341 to 1234.2134.1234-1 using JavaScript?

<script>
    function formatar_valor(strvalor){
        var formatado;
        // formata
        return formatado
    }
    alert(formatar_valor('1234213412341'));
</script>
    
asked by anonymous 20.03.2015 / 05:40

4 answers

9

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

function formatar_valor(strvalor) {
    return strvalor.substring(0, 4) + "." + strvalor.substring(4, 8) + "." + 
             strvalor.substring(8, 12) + "-" + strvalor.substring(12, 13);
}
    
document.body.innerHTML += formatar_valor('1234213412341');
    
20.03.2015 / 05:58
7

You can do this with a for loop, although you find the @bigown 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: link

    
21.03.2015 / 09:19
6

If you want something generic, where you can apply masks 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: link

    
21.03.2015 / 09:53
6

A workaround to address 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'));
    
21.03.2015 / 19:47