【问题标题】:Regex - Replace Brackets Around Numbers With HTML [duplicate]正则表达式 - 用 HTML 替换数字周围的括号 [重复]
【发布时间】:2018-04-30 02:26:51
【问题描述】:

我有一个包含文本的字符串。我想用自定义 html 替换大括号内的任何数字。我不确定这是否可以使用正则表达式。我可以通过以下方式识别数字和括号:

input.replace(new RegExp('\{\d+\}', generateHtml(num));
// not sure how to pass the number found in regex to generateHtml()

例如:

Input string : 'The other day I saw {3} cats'
Output string: 'The other day I saw <span class="num">3</span>'

【问题讨论】:

  • 使用正则表达式\{\d+?\}

标签: javascript regex


【解决方案1】:

可以使用捕获组。

const generalHtml = arg => '<b>' + arg + '</b>'
str = 'The other day I saw {3} cats and {4} dogs';
str.replace(/\{(\d+)\}/g, generalHtml("$1"));
// 'The other day I saw <b>3</b> cats and <b>4</b> dogs'

在这种情况下,正则表达式的(\d+) 部分可以通过"$1" 来引用。

【讨论】:

  • 太棒了,这正是我所需要的。 $1 是我缺少的部分
猜你喜欢
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 2016-11-15
  • 2020-01-07
  • 2011-10-26
  • 2013-03-13
相关资源
最近更新 更多