首页 > 解决方案 > Regex for currency of India Rupee '₹'

问题描述

I need to conditionally add

<span class="highlight"> ... </span>

before and after the following type of strings with the help of regex!
TYPE 1 : ₹ 00,00,000 or ₹ 00.00 or ₹ .00 (INR Currency Value )
TYPE 2 : 00 kW (Some digits followed a space and then by kW)
TYPE 4 : 00 kVA (Some digits followed a space and then by kVA)
TYPE 3 : 000 kVAh (Some digits followed by a space and then kVAh)

Examples:
1. "You Saved ₹ 1,71,252 in 7 days" should change to

You Saved <span class="highlight">₹ 1,71,252</span> in 7 days
  1. "Savings: 203 kW" changes to
Savings: <span class="highlight">203 kW</span>
  1. "Consumption: 225 kVAh" changes to
Consumption: <span class="highlight">225 kVAh</span>

Previously I tried this in Javascript Flavor of regex:

this.tb1 = response["text_block_1"].replace(/(\d|₹|,|kW|kVAh|kVA)/g, '<span class="highlight">$1</span>');

but this isn't satisfying enough because it seems to highlight all numbers in the string. I am new to regex and just can't sum up all the regex into one. Here's a regex I have been able to write for the currency part

this.tb1 = " ₹ 1,71,252 in 7 days".replace(/(?=.*\d)^\₹ ?(([1-9]\d{0,2}(,\d{2,3})*)|0)?(\.\d{1,2})?$/, '<span class="highlight">$1</span>');

but unfortunately this also doesn't work!

标签: javascriptregex

解决方案


你可以使用这个正则表达式,

(₹\s+\d+(?:,\d+)*|\d+(?:,\d+)*\s+(?:kW|kVAh?))

并替换为,

<span class="highlight">$1</span>

演示

JS代码演示,

var arr = ['You Saved ₹ 1,71,252 in 7 days','Savings: 203 kW','Consumption: 225 kVAh']

for (s of arr) {
  console.log(s.replace(/(₹\s+\d+(?:,\d+)*|\d+(?:,\d+)*\s+(?:kW|kVAh?))/g, '<span class="highlight">$1</span>'));
}


推荐阅读