我正在尝试这个
str = "@a@b";
str2 = str.replace(/@/g,'-[' + str + ']');
输出应该是 -[a]-[b]
最佳答案
您可以搜索 @
而不是 @
,如下所示,然后替换该组。
/@([^@]+)/g
@ look for this character literately
( ) group, this is the part used for replacing -> $1 in replacement string
[^@]+ look for one or more not @ characters
g global flag, replace all found matches
替换是用第一组$1
进行的。
var str = "@a@b",
str2 = str.replace(/@([^@]+)/g,'-[$1]');
console.log(str2);
关于javascript - 将字符串替换为javascript正则表达式中的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49231478/