[英]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 方法作为结果,然后在使用 ng-href 的 URL 中使用:
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 方法最终停止工作,我该如何解决这个问题?
等效的是substring()
检查 MDN 文档
Use split
and join
on the dot, and during the time you manipulate an array, use slice
to remove the last item: 在点上使用
split
和join
,在操作数组期间,使用slice
删除最后一项:
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. /^\\d+\\.\\d+/
将匹配前两位,中间用点号。
The regex
will not have to process the entire input like the split
approaches do. regex
不必像split
方法那样处理整个输入。
It will also catch consecutive .
它还将连续捕获
.
like 30..40
. 像
30..40
。 And spaces. 和空格。
It will even catch alphabetic parts like 10.B
它甚至会捕获像
10.B
这样的字母部分
This also will extend if you want to start allowing segments such as -alpha
, -beta
, etc. 如果您要开始允许
-alpha
, -beta
等段,这也将扩展。
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.