Reputation: 2059
How can I:
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.
Upvotes: 9
Views: 5280
Reputation:
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.org/ecma-262/6.0/#sec-get-regexp.prototype.flags.
If your intent in doing this is to serialize the regexp, such as into JSON, and then deserialize it back, I would recommend 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.
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);
Upvotes: 7
Reputation: 369134
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.
Upvotes: 3
Reputation: 5616
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())
Upvotes: 3