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

时间:2018-04-30 02:26:52

标签: javascript regex

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

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>'

1 个答案:

答案 0 :(得分:0)

可以使用捕获组。

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"部分。