Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - converting RegExp to String then back to RegExp

So I have a RegExp regex = /asd/

I am storing it as a as a key in my key-val store system.

So I say str = String(regex) which returns "/asd/".

Now I need to convert that string back to a RegExp.

So I try: RegExp(str) and I see //asd//

this is not what I want. It is not the same as /asd/

Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g

Is there a better way to do this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you don't need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.

var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");

If you do need to store the modifiers, use a regex to parse the regex:

var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = //(.*)/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);

This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.

If performance is a concern, use normal string manipulation using String#lastIndexOf:

var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...