Search code examples
javascriptregexsuperscript

Superscript cents in dynamic text string using vanilla JavaScript


I'm trying to superscript the cents in some prices; the prices are dynamic so I can't manually add the sup tags in the HTML.

As far as I know, the prices should be formatted like "3,99 €" but I don't want anything to break if they're changed to something like "€3.99" in the future.

I was trying to use a RegEx like

  var matcher = /(\.|\,)\d{2}(?![\d])/;
  return price.replace(matcher, '<sup>' + matcher + '</sup>');

but I haven't quite figured out how to get only the cents value wrapped between the superscript tags. Any suggestions would be much appreciated.


Solution

  • This should do it: (\d[,.])(\d{2})(?!\d). An extra capture group is needed to allow more characters to be matched while not being replaced (a workaround for positive lookbehind).

    var regex = /(\d[,.])(\d{2})(?!\d)/g;
    var str = 'Test test test 100,99€ test 2.116.600,99€ test € 2,50 test.';
    
    console.log(str.replace(regex, '$1<sup>$2</sup>'));

    Explanation:

    (\d[,.]) | Capture a digit followed by "," or "."
    (\d{2})  | Capture the two cents digits
    (?!\d)   | Ensure a digit doesn't follow the previous capture
    

    Try it here