You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript+正则表达式为HTML中的美元金额添加颜色样式

Solution to Wrap Dollar Amounts in Styled Span Tags

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 g flag 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—match holds the exact dollar string we found (like $100 or $29.99).
  • To make the styled amounts visible, add CSS for the .accent class:
    .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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:13:30