Javascript删除Regex分隔符


Javascript remove Regex Delimiter

我的PHP代码根据用户输入生成JSON。

在这个JSON中,我有一个带有分隔符的Regex字符串"/Regex/gi"。

我将此消息发送给用户,并希望javascript测试基于该正则表达式的字符串。但由于我在字符串中有分隔符,所以它不起作用。

有时,我可以接收到regex字符串为"regex"、"/regex/"或"/regex/gi"那么,有没有一种方法可以删除那些分隔符,或者在正则表达式中转换字符串。

我试着使用"new RegExp",但它转义了字符串,它不起作用。

这里有一些代码:

var json = {regex: "/hello/"}; //This code is generated by PHP
"hello".match(json.regex); //Test in javascript, not working, since the "/" are inside the regex and not used as delimiter 

有人知道我该怎么做吗?

感谢

您可以正则表达式您的正则表达式(woah)

var reMeta = /(^|[^''])'/('w+$){0,1}/;
var json = {regex: "/hello'/slash'//gi"};
json.regex = new RegExp( json.regex.replace(reMeta,'$1') );
// after replace it looks like: "hello'/slash'/"
var json = {regex: "/hello/"};
"hello".match(eval(json.regex));//Simle way (bad practice, but will work)

更多推进方式:

var json = {regex: "hello"};
var reg = new RegExp(json.regex)
var matched = reg.exec("hello") != null;