Skip to content

Instantly share code, notes, and snippets.

@afreeland
Last active December 15, 2015 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afreeland/5254564 to your computer and use it in GitHub Desktop.
Save afreeland/5254564 to your computer and use it in GitHub Desktop.
JavaScript: Keywords array to Regular Expression
/**
* 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