如何用JavaScript+正则表达式为HTML中的美元金额添加颜色样式
Got it, let's tackle this problem. Here's a straightforward implementation of the colorMoney function that does exactly what you need:
function colorMoney(text) { // Regex to match dollar amounts (with $, supports integers or decimals) const moneyRegex = /\$[0-9]+\.*[0-9]*/g; // Replace each matched amount with the styled span tag return text.replace(moneyRegex, match => `<span class='accent'>${match}</span>`); } // Test cases to verify functionality console.log(colorMoney("I have $100 in my bank account right now")); // Output: "I have <span class='accent'>$100</span> in my bank account right now" console.log(colorMoney("This shirt costs $29.99, shoes are $85, and the hat is $12.5")); // Output: "This shirt costs <span class='accent'>$29.99</span>, shoes are <span class='accent'>$85</span>, and the hat is <span class='accent'>$12.5</span>"
Key Details:
- The
gflag in the regex enables global matching, so it finds every dollar amount in the input string instead of just the first occurrence. - Using a function as the second argument to
String.replace()lets us dynamically wrap each matched amount in the span tag without losing the original value—matchholds the exact dollar string we found (like$100or$29.99). - To make the styled amounts visible, add CSS for the
.accentclass:.accent { color: #2ecc71; /* Green example, adjust to your preferred color */ font-weight: 600; /* Optional: Bold for extra emphasis */ }
Optional: Rigorize the Regex
If you want to enforce standard currency formatting (only allow 0 or 2 decimal places, no trailing dots like $50.), update the regex to:
const moneyRegex = /\$[0-9]+(\.[0-9]{2})?/g;
This will match $100 and $49.99, but reject $12.5 or $75..
内容的提问来源于stack exchange,提问作者Elijah M
相关产品推荐
相关产品推荐

