Javascript replace()与大小写更改 [英] Javascript replace() with case-change

查看:175
本文介绍了Javascript replace()与大小写更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法更改使用javascript匹配字符串的情况?

Is there an easy way to change the case of a matched string with javascript?

示例

字符串:< li>某事< / li>

正则表达式: /<([\ w] +)[^>] *>。*?< \ / \1> /

我想做的是将匹配$ 1替换为所有大写字母(如果可能,在替换内)。我不完全确定$ 1是有效匹配而不是字符串 - '$ 1'.toUpperCase不起作用。

And what I'd like to do is replace the match $1 to all capital letters (inside the replace if possible). I'm not entirely sure when $1 is a valid match and not a string -- '$1'.toUpperCase doesn't work.

那我该如何回归呢? < LI>东西< /锂> ?方法,而不是正则表达式。

So how would I go about returning <LI>something</li>? The method, not the regex.

推荐答案

您可以将replace方法传递给replacer函数。第一个参数是整个匹配,第二个参数是1美元。因此:

You can pass the replace method a replacer function. The first argument for which is the whole match, the second will be $1. Thus:

mystring.replace(/<([\w]+)[^>]*>.*?<\/\1>/, function(a,x){ 
   return a.replace(x,x.toUpperCase()); 
})

虽然此表单通过进行额外捕获来保存额外操作(应该更快但未检查):

although this form saves the extra operation by making an additional capture (should be faster but haven't checked):

mystring.replace(/<([\w]+)([^>]*>.*?<\/\1>)/, function(a,x,y){ 
   return ('<'+x.toUpperCase()+y); 
})

这篇关于Javascript replace()与大小写更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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