Created
July 24, 2014 12:36
-
-
Save bennadel/97f7530ca0de0523008e to your computer and use it in GitHub Desktop.
Cloning RegExp (Regular Expression) Objects In JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Cloning RegExp (Regular Expression) Objects In JavaScript</title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
/** | |
* I clone the given RegExp object, and ensure that the given flags exist on | |
* the clone. The injectFlags parameter is purely additive - it cannot remove | |
* flags that already exist on the | |
* | |
* @input RegExp - I am the regular expression object being cloned. | |
* @injectFlags String( Optional ) - I am the flags to enforce on the clone. | |
*/ | |
function cloneRegExp( input, injectFlags ) { | |
var pattern = input.source; | |
var flags = ""; | |
// Make sure the parameter is a defined string - it will make the conditional | |
// logic easier to read. | |
injectFlags = ( injectFlags || "" ); | |
// Test for global. | |
if ( input.global || ( /g/i ).test( injectFlags ) ) { | |
flags += "g"; | |
} | |
// Test for ignoreCase. | |
if ( input.ignoreCase || ( /i/i ).test( injectFlags ) ) { | |
flags += "i"; | |
} | |
// Test for multiline. | |
if ( input.multiline || ( /m/i ).test( injectFlags ) ) { | |
flags += "m"; | |
} | |
// Return a clone with the additive flags. | |
return( new RegExp( pattern, flags ) ); | |
} | |
// -------------------------------------------------- // | |
// -------------------------------------------------- // | |
var regex = new RegExp( "http://www.bennadel.com", "i" ); | |
// Clone the regular expression object, but ensure "g" (global) flag is set | |
// (even if it was not set on the given RegExp instance). | |
var clone = cloneRegExp( regex, "g" ); | |
// The clone should now have both the "i" (source) and "g" (injected) flags set. | |
console.log( "Clone:", clone ); | |
</script> | |
</body> | |
</html> |
@krutoo in this case, it would not since I'm actually building a brand-new RegExp
instance, and only copying over the flags and the source pattern.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is it clones lastIndex property of original regexp?