我想将大多数字符串转换为小写,括号内的那些字符除外。将方括号之外的所有内容都转换为小写之后,然后我要删除方括号。因此,将{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/

10-17 02:20