在 JS 中使用正则表达式基于字符串生成 URL



我想用正则表达式基于 JS 中的字符串生成一个 URL

原始字符串

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

预期的网址

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

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

您可以使用:

/(user: (w+))/g

要匹配用户名并将其存储在组中$1 .然后,您可以使用.replace将文本的其余部分替换为所需的 URL,并在字符串末尾使用匹配的组$1

请参阅以下示例:

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);

最新更新