Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
为什么这不起作用?
var str = "nd2(31)jnd"; str = str.replace(/[0-9](/,/[0-9]*(/);
我想用前面的括号替换每个数字: "2(" 和 "2*("
你的正则表达式是错误的,这就是你想要的:
str.replace(/([0-9]+)\(/g, "$1*(");
$1引用 parens 中的第一个匹配项(),您必须转义\(才能匹配它。
$1
()
\(
更新:添加g全局匹配
g
2(3(4+5)) => 2*(3*(4+5))
更新:使其也可以在括号的另一端工作,结合:
str.replace(/(\d+)\(/g, "$1*(").replace(/\)(\d+)/g, ")*$1");