8

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??

Jam12345
  • 133
  • 1
  • 1
  • 7

4 Answers4

16

the equivalent is substring() check the MDN docs

Ali Hussein
  • 169
  • 1
  • 5
2

Use split and join on the dot, and during the time you manipulate an array, use slice to remove the last item:

const inputs = ['9.1.0', '9.2.0', '9.3.0', '9.10.0', '10.1.0', '22.121.130'];

inputs.forEach(input => {
  const result = input.split('.').slice(0, -1).join('.');
  console.log(input, '=>', result);
})

Simple enough and it will work whatever your version number :)

Hoping that will help you!

sjahan
  • 5,720
  • 3
  • 19
  • 42
1

/^\d+\.\d+/ will match the first 2 digits with dot between.

The regex will not have to process the entire input like the split approaches do.

It will also catch consecutive . like 30..40. And spaces.

It will even catch alphabetic parts like 10.B

This also will extend if you want to start allowing segments such as -alpha, -beta, etc.

const rx = /^\d+\.\d+/

const inputs = ['9.1.0', '9.2.0', '9.3.0', '9.10.0', 
'10.1.0', , '22.121.130', '10.A', '10..20', '10. 11', '10 .11'];

inputs.forEach(input => {
  const m = rx.exec(input)
  console.log(input, m ? m[0] : 'not found')
})
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
0

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');
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62