正则表达式 - 用 HTML 替换数字周围的括号



我有一个包含文本的字符串。我想用自定义 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>'

可以使用捕获组。

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"引用。