代码之家  ›  专栏  ›  技术社区  ›  Three Year Old

如何仅在捕获组不为空的情况下插入特定字符?复制

  •  0
  • Three Year Old  · 技术社区  · 1 年前

    给定以下字符串:

    var string1 = "Chapter_1";
    var string2 = "Chapter_1a";
    

    期望的结果是:

    "Chapter 1."
    "Chapter 1. a)"
    

    我可以这样做:

    var string1new = string1.replace("_", " ").replace(/(\d+)/, "$1.").replace(/.(\w)$/, ". $1)"));
    var string2new = string2.replace("_", " ").replace(/(\d+)/, "$1.").replace(/.(\w)$/, ". $1)"));
    

    但我更喜欢一个单一的模式/替代品。类似于:

    var string1new = string1.replace(/(Chapter)_(\d+)(\w*)/, "$1 $2. $3)");
    var string1new = string1.replace(/(Chapter)_(\d+)(\w*)/, "$1 $2. $3)");
    

    现在如何有条件地插入 $3) 取决于 $3 是空的还是不空的?

    2 回复  |  直到 1 年前
        1
  •  2
  •   piwko28    1 年前

    您可以将函数与条件一起使用,而不是使用结果字符串:

    const formatString = str =>
      str.replace(
        /(Chapter)_(\d+)(\w*)/,
        (_, headerName, point, subpoint) =>
          `${headerName} ${point}.${subpoint ? ` ${subpoint})` : ''}`
    );
    var string1new = formatString(string1);
    var string2new = formatString(string2);
    
        2
  •  1
  •   Roko C. Buljan    1 年前

    你不能做 $3) if $3 exists 或者换句话说:内联可选的替换字符( ) ). 要么你定义文字 ) 输出-或者您不这样做。相反,在 String.prototype.replace 回调函数。

    const chapterify = (string) => {
      return string.replace(/(^[^_]+)_(\d+)(\w*$)/, (_, p1, p2, p3) => {
        return `${p1} ${p2}. ${p3 ? p3+")" : ""}`.trim()
      })
    };
    
    console.log( chapterify("Chapter_1") )
    console.log( chapterify("Chapter_1a") )