Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 基于JS中带有正则表达式的字符串生成url_Javascript_Regex - Fatal编程技术网

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

Javascript 基于JS中带有正则表达式的字符串生成url,javascript,regex,Javascript,Regex,我想用正则表达式根据JS中的字符串生成URL 原始字符串 1. (user: john) 2. (user: mary) 预期URL 1. http://www.test.com/john 2. http://www.test.com/mary 基本上,在:之后和之前的所有内容都是用户名,您可以使用: /\(user: (\w+)\)/g 匹配用户名并将其存储在组$1中。然后可以使用.replace将其余文本替换为所需的URL,并在字符串末尾使用匹配的组$1 见下例: const str

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

原始字符串

1. (user: john) 
2. (user: mary)
预期URL

1. http://www.test.com/john
2. http://www.test.com/mary
基本上,在:之后和之前的所有内容都是用户名,您可以使用:

/\(user: (\w+)\)/g
匹配用户名并将其存储在组$1中。然后可以使用.replace将其余文本替换为所需的URL,并在字符串末尾使用匹配的组$1

见下例: const strs=[1.用户:john,2.用户:mary], res=strs.mapstr=>str.replace/\user:\w+\/g,'http://www.test.com/$1';
console.logres;现在很糟糕,但是有耐心和学习的决心,你可以像其他程序员一样成为一名大师:我能够获得团队,但缺少的是替换部分。现在一切都好了。谢谢你,尼克@帅哥,别担心!只有当str不是字符串时,才会出现该错误。。。但是,要从表达式中仅获取组,可以使用/\user:\w+\/g.exec1。用户:john[1]。在这种情况下,你会得到约翰