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.