converting RegExp to String then back to RegExp

前端 未结 5 1922
忘了有多久
忘了有多久 2020-12-17 07:31

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 retur

5条回答
  •  感动是毒
    2020-12-17 08:05

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

提交回复
热议问题