javascript new regexp from string

Spread the love

Question Description

I am trying to create something similar to this:

var regexp_loc = /e/i;

except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn’t get what i wanted.

Basically I want the e in the above regexp to be a string variable but I fail with the syntax.

I tried something like this:

var keyword = "something";

var test_regexp = new RegExp("/" + keyword + "/i");

Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.

regards,
alexander

Practice As Follows

You need to pass the second parameter:

var r = new RegExp(keyword, "i");

You will also need to escape any special characters in the string to prevent regex injection attacks.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.