Last active
December 15, 2015 11:39
-
-
Save afreeland/5254564 to your computer and use it in GitHub Desktop.
JavaScript: Keywords array to Regular Expression
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
/** | |
* Takes an array of keywords and turn it into a regular expression | |
* that can be tested to see if a word matches any in the array | |
* irregardless of white space and case | |
* @param {Array} arrKeywords Array of Keywords | |
* @return {RegExp} Regular Expression | |
*/ | |
function createExpression (arrKeywords) { | |
var innerExpression = ''; | |
[].forEach.call(arrKeywords, function (k, index) { | |
innerExpression += k.replace(' ', '\\s?') | |
// Add pipe so other keywords are appended to regex | |
if(index !== arrKeywords.length -1) | |
innerExpression += "|"; | |
}); | |
var regEx = new RegExp('\\b(' + innerExpression + ')', 'i'); | |
return regEx; | |
// FINAL RESULT | |
// /\b(Price|Master\s?Price|Regular\s?Price)/i | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment