Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - Passing regex modifier options to RegExp object

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...