如何将正则表达式转换为String文字并再次返回? [英] How to convert a regular expression to a String literal and back again?
本文介绍了如何将正则表达式转换为String文字并再次返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么办
- 将带有标志的JavaScript RegExp转换为String文字(例如JSON),
- 然后将该文字转换回正则表达式吗?
例如,使用字符串今天天气很好"
:
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 ? */
要修改原始的RegExp属性,请参见 torazaburo的答案.
推荐答案
您可以使用 eval
以获取正则表达式:
You can use eval
to get back the regular expression:
var myRe = RegExp("weather", "gi");
var myReString = myRe.toString();
eval(myReString); // => /weather/gi
注意: eval
可以执行任意的javascript表达式.仅当您确定字符串是从正则表达式 toString生成的时,才使用
eval
方法.
NOTE: eval
can execute arbitrary javascript expression. Use eval
only if you're sure the string is generated from regular expression toString
method.
这篇关于如何将正则表达式转换为String文字并再次返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文