Search code examples
javascriptmethodssubstringangularjs-ng-href

Looking for substring alternative javascript


Basically my problem is I am using the substring method on the variable version for the result then to be used inside a URL using ng-href:

substring(0, 3)
version 9.1.0 = 9.1 (good)
version 9.2.0 = 9.2 (good)
version 9.3.0 = 9.3 (good)
..
version 9.10.0 = 9.1 (breaks here)
version 10.1.0 = 10. (breaks here)

As you can see eventually the substring method stops working, how can I fix this??


Solution

  • You can get the substring the other way by removing the last two character which will be a dot and a numeric character:

    function version(val){
      console.log(val.substring(0,val.length-2))
    } 
    version('9.1.0');
    version('9.2.0');
    version('9.3.0');
    version('9.10.0');
    version('10.1.0');

    But what if there are two numeric character and a dot at the end? Here is that solution:

    function version(val){
      var tempVersion = val.split('.');
      tempVersion.pop();
      console.log(tempVersion.join('.'))
    } 
    version('9.1.0');
    version('9.2.0');
    version('9.3.1020');
    version('9.10.0');
    version('10.1.0123');