0

My code in PHP generate a JSON based on the user input.

Inside this JSON, I have a Regex string "/regex/gi" with the delimiter.

I send this to the user and I would like javascript to test a string based on that regex. But since I have the delimiter inside the string, it does not work.

Sometime, I can receive the regex string as "regex", "/regex/" or "/regex/gi" So is there a way to remove thoses delimiter, or transform the string in a regex.

I tried to use "new RegExp" but it escape the string, and it won't work.

Here some code:

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 

Anyone have an idea how I could do this?

Thank

6
  • code sample will be useful. Commented Jun 25, 2013 at 12:34
  • Some code pls, we neeed to see Commented Jun 25, 2013 at 12:35
  • @balajimca var json = { regex: "/hello/" } //Generated by php, "hello".match(json.regex); //Not working, only work if the string is "/hello/" Commented Jun 25, 2013 at 12:36
  • bro, Can you update your question with your code. Not in comment section :) Commented Jun 25, 2013 at 12:40
  • You should accept one format, otherwise you will bump into problems. I'll show you an example: user1 tries /\/\//, user2 tries /\/\//gi and user3 \/\/ (without delimiters). If we removed the / from the begin and the end, the third user will have a problem. Commented Jun 25, 2013 at 12:43

2 Answers 2

2

You could regex your regex (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\/"
Sign up to request clarification or add additional context in comments.

Comments

1
var json = {regex: "/hello/"};

"hello".match(eval(json.regex));//Simle way (bad practice, but will work)

More propel way:

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

1 Comment

I would highly prefer not to use eval. I tried the new RegExp class, but if the input is "/hello/" RegExp will escape the "/", I need a way to simply remove them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.