This morning, Mathrick pointed out that the RegExp-cloning approach in my Node.js Transform Streams exploration was fairly inadequate. While it wasn't the focus of the blog post (it was about Node.js streams), he was 100% right - my approach only worked coincidentally with my input. And, as someone who loves regular expressions, I felt like I had to make it right. As such, I've created a more durable cloning function below.
Rather than just calling the .toString() method on the input, I am now checking the incoming RegExp instance for both its source (ie, the pattern) and the individual flags that have been set. Now, in my particular use-case, I also wanted to ensure that the clone had the global ("g") flag set. So, I've created an optional parameter - injectFlags - to allow new flags to be injected into the clone during duplication.
Notice that the original RegExp object only has the "i" (caseInsensitive) flag being set; but, as I clone it, I'm injected the "g" (global) flag. When I run this code, I get the following console log output:
Clone: RegExp /http:\/\/www.bennadel.com/ig
As you can see, both flags are present on the cloned regular expression object.
I've tested this in Chrome, Firefox, Safari, and whichever version of IE my VirtualBox instance happen to have installed. It appears to work consistently on each.
Want to use code from this post? Check out the license.
var regex=/.*/g, clone;
// Easy way
// Additional way to add/replace flags