title: how to sort strings in javascript numerically
body: <p>I would like to sort an array of strings (in javascript) such that groups of digits within the strings are compared as integers not strings.  I am not worried about signed or floating point numbers.</p>
  
  <p>for example, the result should be <code>["a1b3","a9b2","a10b2","a10b11"]</code> not <code>["a1b3","a10b11","a10b2","a9b2"]</code></p>
  
  <p>The easiest way to do this seems to be splitting each string on boundaries around groups of digits.  Is there a pattern I can pass to String.split to split on character boundaries without removing any characters?</p>
  
  <p><code>"abc11def22ghi".split(/?/) = ["abc","11","def","22","ghi"];</code></p>
  
  <p>Or is there another way to compare strings that does not involve splitting them up, perhaps by padding all groups of digits with leading zeros so they are the same length?</p>
  
  <p><code>"aa1bb" =&gt; "aa00000001bb", "aa10bb" =&gt; "aa00000010bb"</code></p>
  
  <p>I am working with arbitrary strings, not strings that have a specific arrangement of digit groups.</p>
  
  <p>Edit:</p>
  
  <p>I like the <code>/(\d+)/</code> one liner from Gaby to split the array.  How backwards compatible is that?</p>
  
  <p>The solutions that parse the strings once in a way that can be used to rebuild the originals are much more efficient that this compare function.  None of the answers handle some strings starting with digits and others not, but that would be easy enough to remedy and was not explicit in the original question.</p>
  
  <pre><code>["a100","a20","a3","a3b","a3b100","a3b20","a3b3","!!","~~","9","10","9.5"].sort( function ( inA , inB ) {
      var                     result = 0;
  
      var                     a , b , pattern = /(\d+)/;
      var                     as = inA.split( pattern );
      var                     bs = inB.split( pattern );
      var                     index , count = as.length;
  
      if ( ( '' === as[0] ) === ( '' === bs[0] ) ) {
          if ( count &gt; bs.length ) count = bs.length;
  
          for ( index = 0 ; index &lt; count &amp;&amp; 0 === result ; ++index ) {
              a = as[index]; b = bs[index];
  
              if ( index &amp; 1 ) {
                  result = a - b;
              } else {
                  result = !( a &lt; b ) ? ( a &gt; b ) ? 1 : 0 : -1;
              }
          }
  
          if ( 0 === result ) result = as.length - bs.length;
      } else {
          result = !( inA &lt; inB ) ? ( inA &gt; inB ) ? 1 : 0 : -1;
      }
  
      return result;
  } ).toString();
  </code></pre>
  
  <p>result: <code>"!!,9,9.5,10,a3,a3b,a3b3,a3b20,a3b100,a20,a100,~~"</code></p>