How do I add a US dollar sign to currency numbers on a webpage using a userscript?

66 Views Asked by At

I am trying to add a $ sign to multiple currency values on a webpage that does not contain currency symbols.

For example, I would like 25.00 to be formatted as $25.00. Another example is that I would like 3,100.00 to be formatted as $3,100.00.

I am currently using a userscript in the Violentmonkey browser extension to accomplish this task. For some unknown reason, my current userscript is not formatting the numbers on the webpage.

I tried using a regular expression to hopefully fix the issue, but the numbers remain unformatted despite executing my userscript.


(function() {
    'use strict';

    function checkReadyState() {
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
            // Regex to find numbers with two decimal places (with or without commas)
            const numberRegex = /\d+(,\d+)*\.\d\d/;

            // Find all text nodes (more general than specific elements)
            const textNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
            let currentNode;

            // Function from StackOverflow
            const money = (amount, currency = 'USD', locale = 'en-US') => {
                return Intl.NumberFormat(locale, {
                    style: 'currency',
                    currency
                }).format(amount);
            }

            while (currentNode = textNodes.nextNode()) {
                const text = currentNode.nodeValue;
                const modifiedText = text.replace(numberRegex, (match) => {
                    // Don't add '$' if it already exists
                    if (match.startsWith('$')) {
                        return match;
                    } else {
                        const amount = parseFloat(match.replace(/,/g, '')); // Remove commas
                        return money(amount);
                    }
                });
                if (modifiedText !== text) {
                    const newNode = document.createTextNode(modifiedText);
                    currentNode.parentNode.replaceChild(newNode, currentNode);
                }
            }
        } else {
            // Wait for the document to be ready
            document.addEventListener('DOMContentLoaded', checkReadyState);
        }
    }

    // Call the function initially
    checkReadyState();
})();


    <p>25.00</p>

    <p>3,100.00</p>

    <div data-cellname="[object Object]" class="css-12hdbj5 css-nil">3,105.00</div>
    <br>

    <span data-testid="__global!balance-1a1d49c3-9cb8-4c67-896c-0122ac627f08" data-cellname="__global!balance-1a1d49c3-9cb8-4c67-896c-0122ac627f08" class=" css-1ai95jy">45.14</span>
    <br>

<span class=" css-bs1bqe">90.00</span>
    <br>

1

There are 1 best solutions below

5
Emmanuel Joshua On

JavaScript has an Intl object that exposes the NumberFormat method. With this method, you can create a function that should accept the money to be formatted to $.

const money = (amount, currency = 'USD', locale = 'en-US') => {
    return Intl.NumberFormat(locale, {
        style: 'currency',
        currency
    }).format(amount);
}

You can give the function any name of your choice.

Now, to format the number to $, simply call the function passing the number to it:

let number = 25;
console.log(money(25));
// $25.00

For more, checkout the docs at MDN