这有效:
var r="xS";
var regex = new RegExp(r); // Anchor at the end
var s="axS";
s = s.replace( regex, "Z" );
// Now, s is "aZ"
但这并不
var r="x$";
var regex = new RegExp(r); // Anchor at the end
var s="ax$";
s = s.replace( regex, "Z" );
// Now, s is STILL "ax$". NOT "aZ".
无论“$”位于字符串 r
中的哪个位置,这都不起作用 - 例如,即使它不在末尾。
最佳答案
如果你想在字符串中查找$
,你需要对其进行转义。 $
是正则表达式中的特殊字符,意思是“字符串结尾”。
var r="x\$";
var regex = new RegExp( r + "$" ); // Anchor at the end
关于javascript - 为什么包含 $(从字符串构建)的正则表达式不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9297112/