我有一个像这样的字符串,
(1 AND 2 ) OR (2 AND 3)
我需要用数字+特殊字符(例如1@,2@
)将此字符串替换为所有数字,结果应如下所示,
(1@ AND 2@ ) OR (2@ AND 3@),
所以我尝试了以下方法,
var d = "(1 AND 2 ) OR (2 AND 3)"
console.log(d.replace(/[0-9]/g, "@"))
,但只会产生类似的结果,
(@ AND @ ) OR (@ AND @)
我的预期输出是,
(1@ AND 2@ ) OR (2@ AND 3@)
答案 0 :(得分:5)
尝试使用$&
在输出中包含匹配项:
const str = '(1 AND 2 ) OR (2 AND 3)'
console.log(str.replace(/\d/g, '$&@'));
您还可以在后面使用(新)looklook,这样可以匹配 boundary ,但不匹配数字本身:
const str = '(1 AND 2 ) OR (2 AND 3)'
console.log(str.replace(/(?<=\d)/g, '@'));