Skip to content

Instantly share code, notes, and snippets.

@elclanrs
Created October 15, 2012 08:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elclanrs/3891362 to your computer and use it in GitHub Desktop.
Save elclanrs/3891362 to your computer and use it in GitHub Desktop.
Super Regex, interpolate variables in regular expressions with unicode
// Super RegExp
// @param regex A regular expression as literal or as string
// @param obj And object containing the values to replace inside the regex
// Usage: var regex = sRegExp( /Hello #{a}/, { a: 'World' } )
function sRegExp( regex, obj ) {
regex = regex.toString();
var newRegex = regex.replace(/(^\/|\/$|\/([igm]+)$)/g, '')
.replace( /#\{(\w+)\}/g, function( a,b ) { return obj[b]; });
var mods = regex.match( /\/([igm]+)$/ );
return new RegExp( newRegex, mods ? mods[1] : '' );
}
// Convert a string or character to unicode
function toUnicode( str ) {
return str.replace(/./g, function ( char ) {
return '\\x'+ char.charCodeAt(0).toString(16).toUpperCase();
});
}
// Example:
var pattern = sRegExp(
'/\\b[a-z#{a}-#{b}]+\\b/gi',
{ a: toUnicode('À'), b: toUnicode('ÿ') }
);
console.log( 'Hello año foobar sábado'.match( pattern ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment