【问题标题】:Using regex for apostrophe使用正则表达式作为撇号
【发布时间】:2021-10-15 06:54:20
【问题描述】:

我正在使用这个功能

function capitalizeAllWords(str: string) {
  return str.replace(/\b\w/s, letter => letter.toUpperCase());
  }

当前结果:男士服装

必填结果:男士服装

如何做到这一点?

【问题讨论】:

  • /(?<='s )[a-z]/g 会做到的。
  • 使用/(?:^|\s)\w/g
  • 取决于 OP 如何处理单词边界,除了 ' 这样的东西 ... (?<!'|^)\b\w ... 或不太具体的 ... (?<!')\b\w ... 会做它。

标签: javascript regex typescript regression


【解决方案1】:

使用

function capitalizeAllWords(str: string) {
  return str.replace(/(?<![\w'])\w/g, letter => letter.toUpperCase());
}

解释

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    [\w']                    any character of: word characters (a-z,
                             A-Z, 0-9, _), '''
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \w                       word characters (a-z, A-Z, 0-9, _)

注意g 标志替换所有匹配项,而不是s

【讨论】:

    【解决方案2】:

    可以使用replace方法的回调。

    function capitalizeAllWords(str: string) {
        return str.replace(/'[a-z]|\b([a-z])/g, (m, g1) => g1 ? g1.toUpperCase() : m);
    }
    

    在第 1 组中捕获您想要大写的内容(在示例代码中由 g1 表示),并匹配您想要保持不变的内容(在示例代码中由 m 表示)

    '[a-z]|\b([a-z])
    

    说明

    • '[a-z] 匹配 ' 和一个字符 a-z
    • |或者
    • \b([a-z]) 一个字边界\b 防止部分匹配,并在组 1 中捕获一个字符 a-z

    Regex demo

    const regex = /'[a-z]|\b([a-z])/g;
    const str = "Men's apparel $test";
    let res = str.replace(regex, (m, g1) => g1 ? g1.toUpperCase() : m);
    console.log(res);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2015-07-26
      相关资源
      最近更新 更多