title: Regular Expression (Javascript) - Take a scrambled word and find an unscrambled match
body: <p>I have a list of all the words in the English dictionary (270,000+ words) stored in a variable called <code>theList</code>.
  I have a scrambled word <code>word</code> that I want to unscramble by matching against the word list.
  Initially, I thought that the following code would do the trick, but it doesn't work so well.</p>
  
  <pre><code>var theList; // Contains all the words in the English dictionary.
  
  var word = "iexospensr"; // The word I want to unscramble.
  
  var matches = word.match(new RegExp("^["+word+"]{"+word.length+"}$", "gim"));
  </code></pre>
  
  <p>I'd have expected "EXPRESSION" as the unscrambled result, but I instead get a lot more results (listed below).</p>
  
  <p><code>EERINESSES,EXPRESSERS,EXPRESSION,IRONNESSES,ISOSPORIES,NONPERSONS,NONPROSSES,NOSINESSES,OPENNESSES,OPPRESSION,OPPRESSORS,ORNERINESS,PENSIEROSO,PENSIONEER,PENSIONERS,PEPPERONIS,PERSIENNES,PERSONISES,PIPINESSES,PIXINESSES,POORNESSES,PORINESSES,POSSESSION,POSSESSORS,PREEXPOSES,PREPOSSESS,PREPPINESS,PRESENSION,PRIORESSES,PRISSINESS,PROPENSION,PROPERNESS,REINSPIRES,REPRESSERS,REPRESSION,REPRESSORS,RESERPINES,RESPONSERS,RESPONSORS,RIPENESSES,ROPINESSES,ROSINESSES,SERENENESS,SEXINESSES,SIXPENNIES,SNIPPINESS,SORENESSES,SPINNERIES</code></p>
  
  <p>Perhaps, if I could find a way to tell the regular expression to consider each letter in the string <code>word</code> just once irrespective of the order of the letters. So the end result would be an array of combination of those letters, and not permutations (what I have now).</p>
  
  <p>Any help would be appreciated.</p>
  
  <hr>
  
  <p>EDIT: 
  I think the way to go would be:
  1. finding all the combinations of the scrambled word
  2. matching them against the word list to check for validity</p>
  
  <p>If you have a better solution (performance-wise), it'd help.</p>
  
  <hr>
  
  <p>The best solution to this problem seems to be reordering the anagram by alphabet, and the entire word list and matching the word against each item in the list.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>    var textList; // the entire dictionary
      var list = textList.match(/^.*$/gim);
      var sortedList = [];
      list.forEach(function(element, index, array) {
          sortedList[index] = element.split("").sort().join("");
      });
  
      function unscramble(word)
      {
          word = word.toUpperCase().split("").sort().join("");
          var matches = [];
          for (var i = 0; i &lt; list.length; i++) {
              if (word.indexOf(sortedList[i]) &gt;= 0) {
                  if (!matches[list[i].length])
                      matches[list[i].length] = [];
                  matches[list[i].length].push(list[i]);
              }
          }
          return matches;
      }
  </code></pre>