我想将大部分字符串转换为小写,括号内的那些字符除外。将括号外的所有内容转换为小写后,我想删除括号。因此,将 {H}ell{o} World
作为输入应该将 Hello world
作为输出。删除括号很简单,但是有没有办法用正则表达式有选择地使括号外的所有内容小写?如果没有简单的正则表达式解决方案,那么在 javascript 中执行此操作的最简单方法是什么?
最佳答案
你可以试试这个:
var str='{H}ell{o} World';
str = str.replace(/{([^}]*)}|[^{]+/g, function (m,p1) {
return (p1)? p1 : m.toLowerCase();} );
console.log(str);
模式匹配:
{([^}]*)} # all that is between curly brackets
# and put the content in the capture group 1
| # OR
[^{]+ # anything until the regex engine meet a {
# since the character class is all characters but {
回调函数有两个参数:
m
完全匹配
p1
第一个捕获组
如果 p1
不为空,则返回 p1
否则整个匹配小写的 m
。
详细信息:
"{H}" p1 contains H (first part of the alternation)
p1 is return as it. Note that since the curly brackets are
not captured, they are not in the result. -->"H"
"ell" (second part of the alternation) p1 is empty, the full match
is returned in lowercase -->"ell"
"{o}" (first part) -->"o"
" World" (second part) -->" world"
关于javascript - 将 toLowerCase 的操作限制为字符串的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17128397/