Created
October 15, 2012 08:13
-
-
Save elclanrs/3891362 to your computer and use it in GitHub Desktop.
Super Regex, interpolate variables in regular expressions with unicode
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
// 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