Javascript / Jquery - 从字符串中获取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3955345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript / Jquery - Get number from string
提问by Alex
the string looks like this
字符串看起来像这样
"blabla blabla-5 amount-10 blabla direction-left"
How can I get the number just after "amount-"
, and the text just after "direction-"
?
我怎样才能得到紧随其后的数字和紧随其后"amount-"
的文本"direction-"
?
回答by Ed.C
This will get all the numbers separated by coma:
这将得到所有由昏迷分隔的数字:
var str = "10 is smaller than 11 but greater then 9"; var pattern = /[0-9]+/g; var matches = str.match(pattern);
After execution, the string matches
will have values "10,11,9"
执行后,字符串matches
将有值"10,11,9"
If You are just looking for thew first occurrence, the pattern will be /[0-9]+/
- which will return 10
如果您只是在寻找第一次出现,则模式将是/[0-9]+/
- 它将返回10
(There is no need for JQuery)
(不需要JQuery)
回答by PleaseStand
This uses regular expressionsand the exec method:
var s = "blabla blabla-5 amount-10 blabla direction-left";
var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
var direction = /direction-([^\s]+)/.exec(s)[1];
The code will cause an error if the amount or direction is missing; if this is possible, check if the result of exec is non-null before indexing into the array that should be returned.
如果缺少金额或方向,代码将导致错误;如果可能,请在索引到应返回的数组之前检查 exec 的结果是否为非空。
回答by Aif
You can use regexp as explained by w3schools. Hint:
您可以按照w3schools 的说明使用正则表达式。暗示:
str = "blabla blabla-5 amount-10 blabla direction-left"
alert(str.match(/amount-([0-9]+)/));
Otherwize you can simply want all numbers so use the pattern [0-9]+ only. str.match would return an array.
否则,您可以简单地想要所有数字,因此仅使用 [0-9]+ 模式。str.match 将返回一个数组。