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

在JS中用regex替换冒号

  •  0
  • Axel  · 技术社区  · 6 年前

    我有以下字符串:

    let str = '/user/:username/'
    

    我想提取替换 username 具有 harry 切除结肠。

    我尝试了以下方法:

    const regex = /[^:]+(?=:)/g
    str.replace(regex, x => console.log(x))
    
    5 回复  |  直到 6 年前
        1
  •  2
  •   mrzasa    6 年前

    尝试: /:\w+/

    let str = '/user/:username/'
    str.replace(/:\w+/, "harry")
    // => "/user/harry/"
    
        2
  •  2
  •   Parth Raval    6 年前

    let str = '/user/:username/';
    let html = str.replace(":username", "harry");
    console.log(html);
        3
  •  1
  •   Paulquappe    6 年前
    var str = '/user/:username/';
    var newstr = str.replace(/:username/i, "harry");
    print(newstr);
    

    嗨,朋友,这是你要找的吗?我发现它在 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/replace

        4
  •  1
  •   sainanky    6 年前

    您可以这样使用:

    let str = '/user/:username/';
    str.replace(':username','harry')
    // o/p => /user/harry/"
    
        5
  •  1
  •   The fourth bird    6 年前

    在你的正则表达式中 [^:]+(?=:) 您匹配的不是冒号的1+次,并断言在末尾应该有一个冒号,这将导致匹配 /user/

    如果要使用否定字符类,可以匹配冒号,然后不匹配正斜杠:

    :[^\/]+
    

    const str = `/user/:username/`;
    const result = str.replace(/:[^\/]+/, "harry");
    console.log(result);