Search code examples
regexgoogle-apps-scriptnumber-formatting

Regex to format number in string using Google Apps script


I'm trying to format numbers in a string in following format: #,##,### Here is my google script code but it replaces the number with #,##,### String can have any number of characters before and after the numbers. What is the best and efficient way to do it?

Input string : "Price starting from Rs.100000, 10% discount " or "Price starting from Rs.100,000, 10% discount" Expected out : "Price starting from Rs.1,00,000, 10% discount"

treated_value3 = treated_value2.replace(/(\d+)/, Utilities.formatString("#,##,##0","$1"));

Solution

  • Use Intl:

    const str = "Price starting from Rs.100000",
    str2 =  "Price starting from Rs.100,000",
    str3 = "Pricing starts at Rs.50000000 and get 20% discount, if you order now!";
    [str, str2, str3].forEach(str=>{
        const [,prefix, num, suffix] = str.match(/(.*?Rs\.)([\d,]+)(.*)$/);
        const fNum = new Intl.NumberFormat('en-IN').format(num.replace(/,/g,''));
        console.info(`${prefix}${fNum} ${suffix}`);
    })

    Alternatively, Use positive look behinds with string.replace:

    const str = 'Price starting from Rs.100000',
      str2 = 'Price starting from Rs.100,000',
      str3 =
        'Pricing starts at Rs.50000000 and get 20% discount, if you order now!';
    [str, str2, str3].forEach(str => {
      const formatted = str.replace(/(?<=Rs\.)[\d,]+/, num => {
        return new Intl.NumberFormat('en-IN').format(num.replace(/,/g, ''));
      });
      console.info(formatted);
    });