Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created July 24, 2014 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bennadel/97f7530ca0de0523008e to your computer and use it in GitHub Desktop.
Save bennadel/97f7530ca0de0523008e to your computer and use it in GitHub Desktop.
Cloning RegExp (Regular Expression) Objects In JavaScript
<!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
Copy link

krutoo commented Dec 7, 2022

Is it clones lastIndex property of original regexp?

@bennadel
Copy link
Author

bennadel commented Dec 7, 2022

@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