在捕获组(JavaScript)上应用toUpperCase()

时间:2017-01-14 20:46:57

标签: javascript regex tags

我有字符串:<upcase>yellow submarine</upcase> 我想使用正则表达式将其修改为:YELLOW SUBMARINE

到目前为止我尝试的是:

var modified = string.replace(/<upcase>(.*?)<\/upcase>/gi, $1.toUpperCase());

和...

var modified = string.replace(/<upcase>(.*?)<\/upcase>/gi, "\U$1");

显然这两种方法都行不通,那么这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

更新了以仅获得“黄色潜水艇”

请参阅documentation了解

var str = '<upcase>yellow submarine</upcase>';
str = str.replace(/<upcase>(.*?)<\/upcase>/gi, function(){return arguments[1].toUpperCase()});
console.log(str);

答案 1 :(得分:0)

经过一番研究后,我自己找到了解决方案。如果有人有兴趣:

var str = '<upcase>yellow submarine</upcase>';
str = str.replace(/<upcase>(.*?)<\/upcase>/gi, function (v) {
    return v.replace(/<\/?[^>]+(>|$)/g, "").toUpperCase();
});