Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Couldn't find a function doing what I wanted here. So I wrote my own. This is my contribution. I hope someone find it useful.</p> <p><strong>Pros:</strong></p> <ul> <li><p>Handles version strings of arbitrary length. '1' or '1.1.1.1.1'.</p></li> <li><p>Defaults each value to 0 if not specified. Just because a string is longer doesn't mean it's a bigger version. ('1' should be the same as '1.0' and '1.0.0.0'.)</p></li> <li><p>Compare numbers not strings. ('3'&lt;'21' should be true. Not false.)</p></li> <li><p>Don't waste time on useless compares in the loop. (Comparing for ==)</p></li> <li><p>You can choose your own comparator.</p></li> </ul> <p><strong>Cons:</strong></p> <ul> <li>It does not handle letters in the version string. (I don't know how that would even work?)</li> </ul> <p><strong>My code, similar to the accepted answer by <em>Jon</em>:</strong></p> <pre><code>function compareVersions(v1, comparator, v2) { "use strict"; var comparator = comparator == '=' ? '==' : comparator; if(['==','===','&lt;','&lt;=','&gt;','&gt;=','!=','!=='].indexOf(comparator) == -1) { throw new Error('Invalid comparator. ' + comparator); } var v1parts = v1.split('.'), v2parts = v2.split('.'); var maxLen = Math.max(v1parts.length, v2parts.length); var part1, part2; var cmp = 0; for(var i = 0; i &lt; maxLen &amp;&amp; !cmp; i++) { part1 = parseInt(v1parts[i], 10) || 0; part2 = parseInt(v2parts[i], 10) || 0; if(part1 &lt; part2) cmp = 1; if(part1 &gt; part2) cmp = -1; } return eval('0' + comparator + cmp); } </code></pre> <p><strong>Examples</strong>:</p> <pre><code>compareVersions('1.2.0', '==', '1.2'); // true compareVersions('00001', '==', '1.0.0'); // true compareVersions('1.2.0', '&lt;=', '1.2'); // true compareVersions('2.2.0', '&lt;=', '1.2'); // false </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload