Remove semicolon from a JS string

Asked

Viewed 1,074 times

-2

Hi, I was wondering if there’s something wrong with that function that won’t let me remove the semicolon from the string. What happens is that I have an input that when receiving the entered value it formats the typed text to the BRL standard

console.log(moneyMask(1579846));

saída: 
15.798,46;

So far, so good but if I add more digits the output is like this:

console.log(moneyMask(15.798,4656));

saída: 
15.798,46,56;

Here is the function code:

static moneyMask(value) {
        let tmp = value + '';
        tmp.replace(/[\D]+/g, '');
        tmp = tmp.replace(/([0-9]{2})$/g, ',$1');
        if (tmp.length > 6) {
            tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, '.$1,$2');
        }
        if (tmp.length > 9) {
            tmp = tmp.replace(/([0-9]{3}).([0-9]{3}),([0-9]{2})$/g, '.$1.$2,$3');
        }
        return tmp;
    }

Note that the tmp.replace(/[\D]+/g, ''); should clear the semicolon.

2 answers

1


Number formatting is not something you need to invent the wheel, unless you really want to. In addition to several ready-made classes, you can use native JS methods to do this, already supported by browsers with PT-BR support.

Example:

const number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 €"

// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "¥123,457"

// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// expected output: "1,23,000"

A good read that will help you a lot:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

0

I found the solution simply dying to look finally found one that would replace:

const v = ((value.replace(/\D/g, '') / 100).toFixed(2) + '').split('.');

        const m = v[0].split('').reverse().join('').match(/.{1,3}/g);

        for (let i = 0; i < m.length; i++) {
            m[i] = m[i].split('').reverse().join('') + '.';
        }

        const r = m.reverse().join('');

        return r.substring(0, r.lastIndexOf('.')) + ',' + v[1];
  • "dying to search" just 25 minutes after asking? https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83Quest

  • "just 25 minutes after asking" like I was looking after I asked the question '-' I spent the whole morning looking. If you’re not going to comment on something constructive, don’t comment on it

Browser other questions tagged

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