The use case is I want to compare a query string of characters to an array of words, and return the matches. A match is when a word contains all the characters in the query string, order doesn't matter, repeated characters are okay. Regex seems like it may be too powerful (a sledgehammer where only a hammer is needed). I've written a solution that compares the characters by looping through them and using indexOf, but it seems consistently slower. (http://jsperf.com/indexof-vs-regex-inside-a-loop/10) Is Regex the fastest option for this type of operation? Are there ways to make my alternate solution faster?
var query = "word", words = ['word', 'wwoorrddss', 'words', 'argument', 'sass', 'sword', 'carp', 'drowns'], reStoredMatches = [], indexOfMatches = []; function match(word, query) { var len = word.length, charMatches = [], charMatch, char; while (len--) { char = word[len]; charMatch = query.indexOf(char); if (charMatch !== -1) { charMatches.push(char); } } return charMatches.length === query.length; } function linearIndexOf(words, query) { var wordsLen = words.length, wordMatch, word; while (wordsLen--) { word = words[wordsLen]; wordMatch = match(word, query); if (wordMatch) { indexOfMatches.push(word); } } } function linearRegexStored(words, query) { var wordsLen = words.length, re = new RegExp('[' + query + ']', 'g'), match, word; while (wordsLen--) { word = words[wordsLen]; match = word.match(re); if (match !== null) { if (match.length >= query.length) { reStoredMatches.push(word); } } } }