Javascript 将字符串转换为正则表达式
我从服务器获取正则表达式字符串。比如说Javascript 将字符串转换为正则表达式,javascript,regex,Javascript,Regex,我从服务器获取正则表达式字符串。比如说 js_pattern = "/^9\d+$/" // true, because it's non-special so it gets evaluated to that character. console.log("\a" === "a"); // true // false, because it's the new line special character. console.log("\n" === "n"); // false 我需要
js_pattern = "/^9\d+$/"
// true, because it's non-special so it gets evaluated to that character.
console.log("\a" === "a"); // true
// false, because it's the new line special character.
console.log("\n" === "n"); // false
我需要从这个字符串中得到相同的正则表达式(没有任何修改)
re=newregexp(js\u模式)
对我不起作用,因为在这种情况下,我得到了/\/^9d+$\/
在JavaScript中是否有正确的变体可以将字符串转换为正则表达式?试试:
re = new RegExp(js_pattern.slice(1,-1))
更新:
要在不做任何修改的情况下满足限制,以下是一种可能不是最好的方法:
eval(js_pattern)
但是,因为“\”在JavaScript中是转义字符,所以应该在服务器端将“\”替换为“\”
UDDATE:
如果您收到的字符串为“/^9\d+$/”,则无需在服务器端执行任何操作。这实际上取决于服务器端代码,但本质上您的问题是,
\d
在字符串中作为转义字符进行求值。我的解决方案是针对PHP的,但其他服务器端语言也应该有类似的解决方案
// drop the enclosing slashes, either here or in JS land
$jsPattern = addslashes("^9\d+$");
// $jsPattern => "^9\\d+$"
现在在JS端,您可以使用:
var js_exp = new RegExp(js_pattern);
最简单的选择是删除封闭的斜杠,如果可以的话,自己添加一个额外的转义斜杠。任何非特殊字符都会计算为字符串中的该字符
比如说
js_pattern = "/^9\d+$/"
// true, because it's non-special so it gets evaluated to that character.
console.log("\a" === "a"); // true
// false, because it's the new line special character.
console.log("\n" === "n"); // false
解决方案:
在发送服务器之前,请退出服务器上的反斜杠。看起来
\d
没有保留。test
和exec
不可用于stringsHow是否从服务器获取内容?阿贾克斯?@KevinNagurski,是的,阿贾克斯。我为不同的表单字段获取了一组规则。您不能假设它是d
还是\d
问题是\d
以字符串形式分配时正在进行评估。您唯一的实际选择是从服务器端转义它。我无法在服务器端修改此规则(后端专用性),我必须使用此规则进行验证,而且我还没有找到任何正确的变体来执行此操作。而\d
是一种特殊情况,任何规则都可以来自服务器。而且似乎没有正确的方法,只有使用一些黑客