在Javascript中用大写替换正则表达式捕获组 [英] Replace a Regex capture group with uppercase in Javascript

查看:151
本文介绍了在Javascript中用大写替换正则表达式捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在JavaScript中用大写替换捕获组。这是我到目前为止尝试过的一个简化版本,它不起作用:

I'd like to know how to replace a capture group with its uppercase in JavaScript. Here's a simplified version of what I've tried so far that's not working:

> a="foobar"
'foobar'
> a.replace( /(f)/, "$1".toUpperCase() )
'foobar'
> a.replace( /(f)/, String.prototype.toUpperCase.apply("$1") )
'foobar'

你能解释一下这段代码有什么问题吗?

Would you explain what's wrong with this code?

推荐答案

你可以把一个函数传递给替换

You can pass a function to replace.

var r = a.replace(/(f)/, function(v) { return v.toUpperCase(); });

解释

a.replace( /(f)/, "$1".toUpperCase())

在此示例中,您将字符串传递给replace函数。由于您使用的是特殊替换语法($ N抓取第N次捕获),因此您只需提供相同的值。 toUpperCase 实际上是欺骗性的,因为你只是将替换字符串设为大写(这有点无意义,因为 $ 和一个 1 字符没有大写,所以返回值仍然是$ 1

In this example you pass a string to the replace function. Since you are using the special replace syntax ($N grabs the Nth capture) you are simply giving the same value. The toUpperCase is actually deceiving because you are only making the replace string upper case (Which is somewhat pointless because the $ and one 1 characters have no upper case so the return value will still be "$1").

a.replace( /(f)/, String.prototype.toUpperCase.apply("$1"))

信不信由这个表达式的语义是完全一样的。

Believe it or not the semantics of this expression are exactly the same.

这篇关于在Javascript中用大写替换正则表达式捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆