Created
May 8, 2013 14:33
-
-
Save kawanet/5540864 to your computer and use it in GitHub Desktop.
文字列の配列を、記号エスケープしつつ、正規表現オブジェクトに変換する JavaScript 関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {array} array - Array of strings. ex. ["aaa", "bb.cc", "(ddd)"] | |
* @returns {Number} - RegExp object escaped and joined. ex. /aaa|bb\.cc|\(ddd\)/ | |
*/ | |
function array_to_regexp(array, opt) { | |
var re = array.sort(function(a, b) { | |
return b.length - a.length; | |
}).map(function(str) { | |
return str.replace(/\W/g, function(match) { | |
return "\\" + match; | |
}); | |
}).join("|"); | |
return new RegExp(re, opt); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment