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??
等效的是substring()
检查 MDN 文档
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!
/^\\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') })
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.