Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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 正则表达式在括号中查找字符串并替换_Javascript_Regex - Fatal编程技术网

Javascript 正则表达式在括号中查找字符串并替换

Javascript 正则表达式在括号中查找字符串并替换,javascript,regex,Javascript,Regex,我有一个字符串:你好[@someperson](#/path/to/Person)。你好吗?你的咖啡在哪里?[@other Person](#/path/to/other)说你不擅长正则表达式。 我想将所有模式(如[@someperson](#/path/to/Person)替换为someperson) 因此上述示例的最终输出应该是:Hello there Some Person。你好吗?你的咖啡在哪里?另一个人说你不擅长正则表达式。 到目前为止,我已经: > var re = /\[@(

我有一个字符串:
你好[@someperson](#/path/to/Person)。你好吗?你的咖啡在哪里?[@other Person](#/path/to/other)说你不擅长正则表达式。

我想将所有模式(如
[@someperson](#/path/to/Person)
替换为
someperson

因此上述示例的最终输出应该是:
Hello there Some Person。你好吗?你的咖啡在哪里?另一个人说你不擅长正则表达式。

到目前为止,我已经:

> var re = /\[@([\w\s]+)\](\(\S+\))/g
> str.match(re)
> ["[@Some Person](#/path/to/person)", "[@Another Person](#/path/to/another)"]
// matches but not quite what I want.
> str.replace(re, $1)
> "Hello there undefined. How are you? Where is your coffee? undefined said you are not great at regex."
// does not replace as expected.

这是我的名片。我只想使用
str.replace
来获得我想要的。不确定这是否可行。看起来应该是这样。请帮助。

您忘记了$1的双引号:

str.replace(re, "$1")

您忘记了在
$1
周围加上双引号:

str.replace(re, "$1")

您的(不正确)输出是什么?看起来你把1美元当作一个变量。可能只需要用引号括起来。应该是“1美元”,我不是投反对票的人,所以我不能告诉你。我的猜测是因为你没有包含错误的输出,所以理论上我们不知道“出了什么问题”。我想我包含了str.replace的错误输出。但我不会在这条评论线上充斥着猜测,因为这与问题无关。感谢所有帮助过我的人。我的错,我现在在代码块中看到了。(虽然说推测很有趣。可以叫我说“我把它包括在代码块中”:P)它要么在那里,要么不在:)你(不正确)的输出是什么?看起来你把1美元当作一个变量。可能只需要用引号括起来。应该是“1美元”,我不是投反对票的人,所以我不能告诉你。我的猜测是因为你没有包含错误的输出,所以理论上我们不知道“出了什么问题”。我想我包含了str.replace的错误输出。但我不会在这条评论线上充斥着猜测,因为这与问题无关。感谢所有帮助过我的人。我的错,我现在在代码块中看到了。(虽然说猜测有点可笑。打电话给我说“我把它包括在代码块中”没关系:P)它要么在那里,要么不在:)谢谢!难以置信的非常感谢。难以置信的