JavaScript match against array

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

提交回复
热议问题