我正在研究这个脚本,它可以让您使用插值变量构建正则表达式。目前我得到了这个,它工作得很好:
function sRegExp( regex, vars ) {
  vars = Array.prototype.slice.call( arguments, 1 );
  regex = regex.toString();
  var newRegex = regex.replace(/(^\/|\/$|\/([igm]+)$)/g, '')
    .replace( /#\{(\d)\}/g, function( a, b ) { return vars[ +b ]; });
  var mods = regex.match( /\/([igm]+)$/ );
  return new RegExp( newRegex, mods ? mods[1] : '' );
}
我像这样使用它:
function func() {
  var foo = 'lol';
  return sRegExp( /baz #{0}/i, foo );
}
console.log( func() ); //=> /baz lol/i
我想通过使用变量名来改进这个脚本,而不是使用索引并将变量作为参数传递,所以我想到了使用eval,所以我去掉vars并重构了代码:
function sRegExp( regex ) {
  regex = regex.toString();
  var newRegex = regex.replace(/(^\/|\/$|\/([igm]+)$)/g, '')
   .replace( /#\{(\w+)\}/g, function( a, b ) { return eval( b ); });
                 __^__                               __^__
  var mods = regex.match( /\/([igm]+)$/ );
  return new RegExp( newRegex, mods ? mods[1] : '' );
}
上一个示例现在的问题是:
console.log( func() ); //=> foo is not defined
但在全球范围内...
var foo = 'lol';
function func() {
  return sRegExp( /baz #{foo}/i );
}
console.log( func() ); //=> /baz lol/i
如何设置eval. 我试过eval.call(func)了,但这显然没有用。有任何想法吗?