Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Super Regex, interpolate variables in regular expressions with unicode

View sRegExpWithUnicode.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// 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
Something went wrong with that request. Please try again.