JavaScript match against array

后端 未结 4 1944
被撕碎了的回忆
被撕碎了的回忆 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: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.} regexs non multiline, non-global regexs.
     * @return {RegExp} a global regex.
     */
    

提交回复
热议问题