2

I am using RegExp on a pattern after reading it from a json file.

json file : 
patternToSearch : {
"test" : "/^test/g"
}

In js file I am using this pattern to match with a string

var patternToMatch = "testing";

var pattern = new RegExp(file.patternToSearch[test]);
console.log(pattern.test(patternToMatch);

I get the output as false as instead of /^test/g the pattern is coming out as /\/^test\/g/.

Not able to remove the extra slahes. Could somebody help me out in this?

1
  • 2
    ['test'] I guess test here should be a string instead of a variable. Commented May 7, 2018 at 7:38

4 Answers 4

1

In your code test is not defined in your case.

var pattern = new RegExp(file.patternToSearch[test]);
                                              ^  ^

You have to replace test with a "test". So this like of code should looks like

var pattern = new RegExp(file.patternToSearch["test"]);

It works too:

var pattern = new RegExp(file.patternToSearch.test);
Sign up to request clarification or add additional context in comments.

Comments

1

try this:

var pattern = new RegExp(file.patternToSearch[test].replace(/^\/|\/$/g,''));

because:

console.log(`/\/^test\/g/`.replace(/^\/|\/$/g, ''))

Single\doesn't matter while / matters.

And I don't know why you didn't get error using patternToSearch[test].It should be patternToSearch.test unless you have defined variable test.

So i would suggest you try this:

var pattern = new RegExp(file.patternToSearch.test.replace(/^\/|\/$/g,''));

Comments

1

You have seen from other answers that accessing a key without treating it as a string is wrong. Besides, you should split your original regex into two parts: patterns and flags then use them in a RegExp constructor:

var patternToSearch = {"test":"/^test/g"};
var source = patternToSearch.test.match(/\/(.*)\/(.*)/);
// source[1] contains patterns, source[2] contains flags
var pattern = new RegExp(source[1], source[2]);
// Logging our tests
console.log(pattern.test("testing"));
console.log(pattern.test("not-testing"));

But before doing this, you have to make sure that tokens and escaped characters are double escaped.

2 Comments

I am reading it from a json file and "patternToSearch" has more keys so can't access it directly with .test.
That's a thing you should find out. Your main problem is dealing with regex that I tried to make it clear.
0

Try this code

new RegExp("\^test", "g")

I got it from here

Comments

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.