我正试图以某些价格上标美分;价格是动态的,因此我无法在HTML中手动添加sup标签。
据我所知,价格的格式应为“ 3,99€”,但我不希望将来将价格更改为“ 3.99€”。
我正尝试使用
之类的RegEx
var matcher = /(\.|\,)\d{2}(?![\d])/;
return price.replace(matcher, '<sup>' + matcher + '</sup>');
但是我还没有弄清楚如何只获取包裹在上标标记之间的美分值。任何建议将不胜感激。
答案 0 :(得分:1)
应该这样做:(\d[,.])(\d{2})(?!\d)
。需要一个额外的捕获组,以允许在不替换的情况下匹配更多字符(正向查找的替代方法)。
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>'));
说明:
(\d[,.]) | Capture a digit followed by "," or "."
(\d{2}) | Capture the two cents digits
(?!\d) | Ensure a digit doesn't follow the previous capture