javascript – 将toLowerCase的操作限制为字符串的一部分?

前端之家收集整理的这篇文章主要介绍了javascript – 将toLowerCase的操作限制为字符串的一部分?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想将大多数字符串转换为小写,除了括号内的那些字符.将括号外的所有内容转换为小写后,我想删除括号.因此,将{H} ell {o}世界作为输入应该将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 {

回调函数有两个参数:

完全匹配

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相关文章