使用Javascript正则表达式更改案例 [英] Change case using Javascript regex

查看:57
本文介绍了使用Javascript正则表达式更改案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 String.replace()中更改某些反向引用的大小写?我希望匹配文本中的某些部分并将其大小写更改为更高/更低。

How to change case of some backreference in String.replace()? I want to match some part in text and change its case to upper/lower.

推荐答案

您可以使用正则表达式进行匹配然后传递一个函数,这是一个转换CSS属性的例子:

You can use a regex for your match then pass a function, here's an example for converting CSS properties:

"margin-top".replace(/-([a-z])/, function(a, l) { return l.toUpperCase(); })
//result = "marginTop"

您可以在此处进行测试。这个正则表达式采用任何 -alpha (一个字符)并将其转换为 -upperalpha ,这只是一个例子,正则表达式有效,您需要调用 。 toUpperCase() .toLowerCase() (或其他任何其他内容)回调中的 second 参数,即当前匹配。

You can test it out here. This regex takes any -alpha (one character) and turns it into -upperalpha, it's just an example though, any regex works, and you'll want to call .toUpperCase() or .toLowerCase() (or anything else really) on the second argument in the callback, which is the current match.

这篇关于使用Javascript正则表达式更改案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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