代码之家  ›  专栏  ›  技术社区  ›  Costantin

正则表达式符号后的非转换字符为大写

  •  0
  • Costantin  · 技术社区  · 7 年前

    我正在尝试将一系列句子转换为标题格。但问题是,使用此正则表达式,如果字符以符号开头,则不会转换字符。我怎样才能让它工作?

    var ls = ["this is fine" "+this is not"]
    var response = ls.map(s => s.toLowerCase().replace(/^(.)|[^\w-'](\w)/gi, match => match.toUpperCase()))
    

    我希望得到的回应是 ["This Is Fine" "+This Is Not"] 而不是 ["This Is Fine" "+this Is Not"] 就像现在一样。

    换句话说,问题在于 +this 没有资本化。如果我加上 "[this is a string]"

    有什么想法吗?

    4 回复  |  直到 7 年前
        1
  •  1
  •   vrintle Jake    7 年前

    你可以使用 \b metacharacter ,它在任何单词边界上都匹配。

    然后正则表达式变为:

    \b\w
    

    i、 e.“匹配单词边界后的任何单词字符。”

    在行动中看到它:

    var ls = ["this is fine", "+this is not"];
    var result = ls.map(s => s.toLowerCase().replace(/\b\w/gi, match => match.toUpperCase()));
    console.log(result);
        2
  •  0
  •   Wiktor Stribiżew    7 年前

    我知道你想匹配一个单词开头的字母,而这个单词前面没有冠词 - ' .

    因此,您可以使用

    var ls = ["this is fine","+this is not", "man-of-war here", "I'm not"]
    var response = ls.map(s => s.toLowerCase().replace(/(^|[^-'])\b([a-z])/g, 
        (_, g1, g2) =>  `${g1}${g2.toUpperCase()}`))
    console.log(response);

    图案会匹配的

    • (^|[^-']) -组1:字符串或除 - 和 '
    • \b -词界
    • ([a-z]) -单个ASCII小写字母
        3
  •  0
  •   The fourth bird    7 年前

    可以在字符串开头匹配单词字符,也可以先不匹配单词字符,然后再匹配单词字符:

    ^\w|\W(\w)

    var ls = ["this is fine", "+this is not"];
    var response = ls.map(s => s.toLowerCase().replace(/^\w|\W(\w)/g, match => match.toUpperCase()))
    console.log(response);
        4
  •  0
  •   Code Maniac    7 年前

    你可以试试这个

    ^\W?\w|\W\w
    

    解释

    • ^ -锚定到字符串的开头。
    • \W?\w -匹配任何非单词字符。(?使其成为可选的)。后跟任何单词字符。
    • | -交替的工作原理与逻辑OR相同。
    • \W\w -匹配后跟单词字符的任何非单词字符。

    Demo

    var ls = ["this is fine", "+this is not"]
    var response = ls.map(s => 
       s.toLowerCase().replace(/^\W?\w|\W\w/g , 
       match => match.toUpperCase()))
    console.log(response);