从对象键创建正则表达式

Create regex from object keys

本文关键字:正则表达式 创建 对象      更新时间:2023-09-26

如何使用下划线更好地简化以下内容?对于非常简单的事情来说,感觉代码太多了。它从对象键创建一个正则表达式。

var obj = {
   'dog' : 1,
   'cat' : 1,
   'rat' : 1
};
var arr = [], regex;
_.each( obj, function( value, index ){
  arr.push( index );
});
regex = _.reduce( arr, function(){
  return new RegExp( arr.join('|'), 'i' );
});
// console.log( regex ) should output: 
/dog|cat|rat/i 

只需像这样使用Object.keys和本机Array.prototype.join

console.log(new RegExp(Object.keys(obj).join("|"), "i"));

有了_,就会_.keys

console.log(new RegExp(_.keys(obj).join("|"), "i"));

结果将是

/dog|cat|rat/i

我很快发现你不需要为此使用下划线。

 var regex = new RegExp( Object.keys( obj ).join('|'), 'i' );