最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert a regular expression to a String literal and back again? - Stack Overflow

programmeradmin4浏览0评论

How can I:

  1. Convert a JavaScript RegExp with flags to a String literal (think JSON),
  2. And convert that literal back to a regex?

For example with the String "the weather is nice today":

var myRe = new RegExp("weather","gi");
var myReToString = myRe.toString(); // myReToString is now "/weather/gi"

var myReCopy = /* How to get this copy only from myReToString ? */

To modify the original RegExp properties see torazaburo's answer.

How can I:

  1. Convert a JavaScript RegExp with flags to a String literal (think JSON),
  2. And convert that literal back to a regex?

For example with the String "the weather is nice today":

var myRe = new RegExp("weather","gi");
var myReToString = myRe.toString(); // myReToString is now "/weather/gi"

var myReCopy = /* How to get this copy only from myReToString ? */

To modify the original RegExp properties see torazaburo's answer.

Share Improve this question edited May 23, 2017 at 10:28 CommunityBot 11 silver badge asked Jul 2, 2016 at 13:33 user2305193user2305193 2,05920 silver badges44 bronze badges 8
  • 7 My I ask what is the use case for converting regex to string and back again? – swlim Commented Jul 2, 2016 at 13:37
  • 3 Your .replace() method would break any regex that contained a forward slash in the actual expression. Also, your technique assumes the gi flags should always be used. – nnnnnn Commented Jul 2, 2016 at 13:48
  • 2 eval would do it. – Bergi Commented Jul 2, 2016 at 14:03
  • Related: Serialization of RegExp, Can I store RegExp and Function in JSON? – GingerPlusPlus Commented Jul 2, 2016 at 14:46
  • 1 Done. Let me know what you think. Also, feel free to edit your post some more or rollback my changes if you don't like them. – Kyll Commented Jul 3, 2016 at 12:39
 |  Show 3 more ments

3 Answers 3

Reset to default 7

Take a look at the accessor properties on the RegExp prototype such as source and flags. So you can do:

var myRe = new RegExp("weather", "gi")

var copyRe = new RegExp(myRe.source, myRe.flags); 

For the spec see http://www.ecma-international/ecma-262/6.0/#sec-get-regexp.prototype.flags.

Serializing and deserializing regexps

If your intent in doing this is to serialize the regexp, such as into JSON, and then deserialize it back, I would remend storing the regexp as a tuple of [source, flags], and then reconstituting it using new RexExp(source, flags). That seems slightly cleaner than trying to pick it apart using regexp or eval'ing it. For instance, you could stringify it as

function stringifyWithRegexp(o) {
  return JSON.stringify(o, function replacer(key, value) {
    if (value instanceof RegExp) return [value.source, value.flags];
    return value;
  });
}

On the way back you can use JSON.parse with a reviver to get back the regexp.

Modifying regexps

If you want to modify a regexp while retaining the flags, you can create a new regexp with modified source and the same flags:

var re = /weather/gim;
var newre = new RegExp(re.source + "| is", re.flags);

I'm not sure if this code works in all cases, but I'm sure that this can be done using regex:

var regex = new RegExp('^/(.+)/(.*)$')
function stringToRegex(s) {
    var match = s.match(regex)
    return new RegExp(match[1], match[2])
}

var test = new RegExp("weather", "gi")

console.log(stringToRegex(test.toString()))
console.log(stringToRegex(test.toString()).toString() === test.toString())

Debuggex Demo

You can use eval to get back the regular expression:

var myRe = RegExp("weather", "gi");
var myReString = myRe.toString();
eval(myReString); // => /weather/gi

NOTE: eval can execute arbitrary javascript expression. Use eval only if you're sure the string is generated from regular expression toString method.

发布评论

评论列表(0)

  1. 暂无评论