11

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

2
  • use substring(0,version.length-2). This way you'll always trim the last 2 symbols from your version. Commented Feb 21, 2019 at 12:18
  • You should use a Regex. Commented Feb 21, 2019 at 12:22

4 Answers 4

19

the equivalent is substring() check the MDN docs

Sign up to request clarification or add additional context in comments.

Comments

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!

Comments

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')
})

Comments

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.