所以我正在使用城市词典 api,他们的术语可以链接到其他使用 [term] 和 api 的框,我想使它们实际上在 markdown 中超链接,即 term所以我尝试制作一个替换正则表达式来做到这一点我到目前为止做得很好,除了当盒子有多个单词时它不起作用 [space words] 我一直试图找到一个好的正则表达式来匹配它但它最终匹配整个字符串这是我使用的正则表达式,它很好但没有空格
"example [string] with [some] boxes".replace(/(\[(\S+)\])/ig, "$1(https://www.urbandictionary.com/define.php?term=$2)");
最佳答案
您可以使用 /(\[([^\][]+)])/g
正则表达式并替换为 "$&(https://www.urbandictionary.com/define.php?term=$1)"
:
console.log(
"example [string] with [space words] boxes".replace(
/\[([^\][]+)]/g, "$&(https://www.urbandictionary.com/define.php?term=$1)")
);
如果要用 +
替换空格,您可以使用
console.log(
"example [string] with [space words] boxes".replace(
/\[([^\][]+)]/g, (x,y) =>
x + "(https://www.urbandictionary.com/define.php?term=" + y.replace(/\s+/g, "+") + ")")
);
请注意,您无需将整个模式包含在捕获组中,您始终可以借助替换模式中的 $&
占位符访问整个匹配值。因此,建议的模式中只有一个 (...)
。
图案细节
\[
-[
字符([^\][]+)
- 捕获第 1 组:[
和]
以外的任何一个或多个字符(注意[
不必在字符类中进行转义,但]
必须)]
-]
字符(请注意,在字符类]
之外不必转义)。
关于捕捉[框]的JavaScript正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52374809/