Questioner
Questioner

Reputation: 7463

How do I separate a currency symbol from a money value and preserve decimals and commas?

I'm trying to take the output of toLocaleString and do a little extra formatting on it. I started with this code:

displayAmount = 1234.56789
currencyFormatted = displayAmount.toLocaleString('en-US', {style: 'currency', currency: 'USD'});

The value of currencyFormatted becomes:

$1,234.57

Not bad, but for various reasons, I want to be able to add a space between the $ and the 1, and wrap a span around it. So the desired output is:

<span>$</span> 1,234.57

So I added this code, which I derived from other answers on Stack Overflow:

symbolSeparated = currencyFormatted.split(/(\d+)/).filter(Boolean);
myElement.innerHTML = "<span>" + symbolSeparated[0] + "</span> " + symbolSeparated[1];

But, I got:

<span>$</span> 1

I realized that my split was considering commas and decimals as text, and splitting there. I tried some other regex that I found, like /[^0-9\.]+/g, but it mostly seemed to just fail and symbolSeparated[1] would be undefined.

In any case, it doesn't have to be regex, it can be any combination of functions or whatever. The question is, how can I separate the currency symbol from the numerical value, while preserving decimals and commas?

Please note, the currency symbol is not guaranteed to be one character in length (otherwise I could just use substring()). It can be from 1 to 3 characters, so far as I know.

Also, answers not dependant on jQuery are preferred.

Upvotes: 1

Views: 1288

Answers (2)

Afanasii Kurakin
Afanasii Kurakin

Reputation: 3459

One-liner, using String.replace:

myElement.innerHTML = displayAmount.toLocaleString('en-US', {style: 'currency', currency: 'USD'}).replace(/^(\D*)(.*)/, '<span>$1</span> $2')

Upvotes: 1

Chris Baldwin
Chris Baldwin

Reputation: 589

This should do the trick for you. The regular expression /^(\D*)(.*)/ looks for all non-digit characters at the front of the string and saves it in the first matching group and then puts the remainder of the string in the second matching group.

const regex = /^(\D*)(.*)/;

function x() {
    displayAmount = 1234.56789
    currencyFormatted = displayAmount.toLocaleString('en-US', {style: 'currency', currency: 'USD'});


    m = regex.exec(currencyFormatted );
    myElement.innerHTML = "<span>" + m[1] + "</span> " + m[2];
}

Upvotes: 2

Related Questions