Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 896
Jam12345 Avatar asked Mar 25 '26 09:03

Jam12345


2 Answers

the equivalent is substring() check the MDN docs

like image 85
Ali Hussein Avatar answered Mar 26 '26 22:03

Ali Hussein


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!

like image 34
sjahan Avatar answered Mar 26 '26 23:03

sjahan