在捕获组(JavaScript)上应用toUpperCase()
我有字符串:在捕获组(JavaScript)上应用toUpperCase(),javascript,regex,tags,Javascript,Regex,Tags,我有字符串:黄色潜水艇 我想使用正则表达式将其修改为:YELLOW subside 到目前为止,我尝试的是: var modified = string.replace(/<upcase>(.*?)<\/upcase>/gi, $1.toUpperCase()); var modified=string.replace(/(.*)/gi,$1.toUpperCase()); 而且 var modified = string.replace(/<upcase>
黄色潜水艇
我想使用正则表达式将其修改为:YELLOW subside
到目前为止,我尝试的是:
var modified = string.replace(/<upcase>(.*?)<\/upcase>/gi, $1.toUpperCase());
var modified=string.replace(/(.*)/gi,$1.toUpperCase());
而且
var modified = string.replace(/<upcase>(.*?)<\/upcase>/gi, "\U$1");
var modified=string.replace(/(.*)/gi,“\U$1”);
显然,这两种方法都不起作用,那么正确的方法是什么呢?只更新了“黄色潜艇”的版本 有关说明,请参阅
var str='黄色潜水艇';
str=str.replace(/(.*)/gi,function(){返回参数[1].toUpperCase()});
console.log(str)代码>经过一番研究,我自己找到了解决方案。如果有人感兴趣:
var str = '<upcase>yellow submarine</upcase>';
str = str.replace(/<upcase>(.*?)<\/upcase>/gi, function (v) {
return v.replace(/<\/?[^>]+(>|$)/g, "").toUpperCase();
});
var str='黄色潜水艇';
str=str.replace(/(.*)/gi,函数(v){
返回v.replace(/]+(>|$)/g,“”).toUpperCase();
});
将回调传递给。替换。看,比我的解决方案好。谢谢如果您查看(正如我在对您的问题的评论中所指出的),那么您将看到每个捕获组的值作为参数传递给回调。因此您可以编写:str.replace(/(.*)/gi,function(match,g){return g.toUpperCase();})
。