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

基于JS中带有正则表达式的字符串生成url

  •  -1
  • handsome  · 技术社区  · 6 年前

    我想用正则表达式根据JS中的字符串生成URL

    1. (user: john) 
    2. (user: mary)
    

    预期URL

    1. http://www.test.com/john
    2. http://www.test.com/mary
    

    基本上,在:和之前)之后的所有内容都将是用户名

    1 回复  |  直到 6 年前
        1
  •  1
  •   Nick Parsons Felix Kling    6 年前

    您可以使用:

    /\(user: (\w+)\)/g
    

    $1 . 然后你可以用 .replace 用所需URL替换其余文本并使用匹配的组 在字符串的末尾。

    见下例:

    const strs = ["1. (user: john)", "2. (user: mary)"],
    
    res = strs.map(str => str.replace(/\(user: (\w+)\)/g, 'http://www.test.com/$1'));
    console.log(res);