JavaScript match against array

后端 未结 4 1958
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 09:23

I would like to know how to match a string against an array of regular expressions.
I know how to do this looping through the array.
I also know how to do this by ma

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 09:57

    (Many years later)

    My version of @Gaby's answer, as I needed a way to check CORS origin against regular expressions in an array:

    var corsWhitelist = [/^(?:.+\.)?domain\.com/, /^(?:.+\.)?otherdomain\.com/];
    
    var corsCheck = function(origin, callback) {
      if (corsWhitelist.some(function(item) {
        return (new RegExp(item).test(origin));
      })) {
        callback(null, true);
      } 
      else {
        callback(null, false);
      }
    }
    
    corsCheck('otherdomain.com', function(err, result) {
      console.log('CORS match for otherdomain.com: ' + result);  
    });
    
    corsCheck('forbiddendomain.com', function(err, result) {
      console.log('CORS match for forbiddendomain.com: ' + result);  
    });
    

提交回复
热议问题