简体   繁体   中英

javascript regular expression - remove extra slashes from output

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?

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);

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,''));

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.

Try this code

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

I got it from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM