Javascript删除正则表达式分隔符

时间:2013-06-25 12:32:30

标签: php javascript regex json

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

在这个JSON中,我有一个带有分隔符的正则表达式字符串“/ regex / gi”。

我将此发送给用户,我希望javascript根据该正则表达式测试字符串。但是因为我在字符串中有分隔符,所以它不起作用。

有时候,我可以收到正则表达式字符串为“regex”,“/ regex /”或“/ regex / gi” 那么有没有办法删除分隔符,或者在正则表达式中转换字符串。

我尝试使用“新的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 

任何人都知道我该怎么做?

感谢

2 个答案:

答案 0 :(得分:2)

你可以正则表达你的正则表达式(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\/"

答案 1 :(得分:1)

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;