JavaScript match against array

后端 未结 4 1942
被撕碎了的回忆
被撕碎了的回忆 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:31

    How about creating a regular expression on the fly when you need it (assuming the array changes over time)

    if( (new RegExp( '\\b' + array.join('\\b|\\b') + '\\b') ).test(string) ) {
      alert('match');
    }
    

    demo http://jsfiddle.net/gaby/eM6jU/


    For browsers that support javascript version 1.6 you can use the some() method

    if ( array.some(function(item){return (new RegExp('\\b'+item+'\\b')).test(string);}) ) {
     alert('match');
    }
    

    http://jsfiddle.net/gaby/eM6jU/1/

    0 讨论(0)
  • 2020-12-30 09:37

    If you have the literal strings in an array called strings you want to match, you can combine them into an alternation by doing

    new RegExp(strings.map(
        function (x) {  // Escape special characters like '|' and '$'.
          return x.replace(/[^a-zA-Z]/g, "\\$&");
        }).join("|"))
    

    If you don't have only literal strings, you want to combine regular expressions, then you use http://code.google.com/p/google-code-prettify/source/browse/trunk/js-modules/combinePrefixPatterns.js

    /**
     * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
     * matches the union of the sets of strings matched by the input RegExp.
     * Since it matches globally, if the input strings have a start-of-input
     * anchor (/^.../), it is ignored for the purposes of unioning.
     * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
     * @return {RegExp} a global regex.
     */
    
    0 讨论(0)
  • 2020-12-30 09:48

    Is that ok ?

    function checkForMatch(string,array){
        var arrKeys = array.length;
        var match = false;
        var patt;
        for(i=0; i < arrKeys; i++ ){
            patt=new RegExp(" "+array[i]+" ");
            if(patt.test(string))
               match = true;
        }
        return match;
    }
    
    string = "She told me birds can fly and I agreed"; 
    
    var array = new Array();
    array[0] = "dog";  
    array[1] = "cat";  
    array[2] = "bird";  
    array[3] = "birds can fly";
    
    
    alert(checkForMatch(string, array));
    
    0 讨论(0)
  • 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);  
    });
    
    0 讨论(0)
提交回复
热议问题