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

使用javascript替换特定位置中的所有空格

  •  1
  • Tomer  · 技术社区  · 6 年前

    我有一根弦,像:

    image.id."HashiCorp Terraform Team <terraform@hashicorp.com>" 
    AND  image.label."some string"."some other string"
    

    我想将所有空格替换为“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

      image.id."HashiCorp___Terraform___Team___<terraform@hashicorp.com>" 
        AND  image.label."some___string"."some___other___string"
    

    我试过这个:

    text = text.replace(/"(\w+\s+)+/gi, function (a) {
                    return a.replace(' ', _delimiter);
                });
    

    但它只替换了第一个空格,所以我得到: HashiCorp___Terraform Team <terraform@hashicorp.com> . 和 some___other string

    1 回复  |  直到 6 年前
        1
  •  3
  •   Wiktor Stribiżew    6 年前

    你可以使用 /"[^"]+"/g 正则表达式匹配两个 " 然后替换回调方法中的空白字符:

    var text = 'image.id."HashiCorp Terraform Team <terraform@hashicorp.com>" \nAND  image.label."some string"."some other string"';
    var _delimiter = "___";
    text = text.replace(/"[^"]+"/g, function (a) {
              return a.replace(/\s/g, _delimiter);
    });
    console.log(text);

    这个 "[^"]+" 图案匹配 ,则1个或多个字符 " " . 这个 a 变量保存匹配值和 a.replace(/\s/g, _delimiter) 用“分隔符”替换匹配值中的每个空白字符。