作为Web应用程序的一部分,我需要在网站的某些部分中搜索{/d}
或{A-Z}
的实例,并将这些实例替换为放置符号的元素。此符号由给定的类确定。
$(".manaCost").html(function (_, html) {
return html.replace(/{([d]|[A-Z])}/g, "<i class="ms ms-cost ms-$1"></i>")
});
上面的代码仅适用于数字,但是,以我使用的库的工作方式,它要求$1
字母的情况下为小写。值得注意的是,使用我在这里使用的 API,我只需要匹配大写字母,但是它们需要转换为小写字母才能使用它们。
在注入替换标记之前,如何将$1
转换为小写(如果可能的话,最好是这一行(?
我已经尝试使用文字和其他正则表达式选项,但到目前为止没有运气。
试试这个
$(".manaCost").html(function (_, html) {
return html.replace(/{([d]|[A-Z])}/g, function(fullMatch, group1) {return "<i class='ms ms-cost ms-"+ group1.toLowerCase() +"'></i>";})
});
String.prototype.replace((方法可以采用可选的回调函数作为参数,它将用于自定义替换字符串,您可以使用它:
$(".manaCost").html(function (_, html) {
return html.replace(/{([d]|[A-Z])}/g, function(fullMatch, g) {return "<i class='ms ms-cost ms-"+ g.toLowerCase() +"'></i>";})
});