Javascript / Jquery - Get number from string

本小妞迷上赌 提交于 2019-11-27 01:38:07

This uses regular expressions and 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.

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"

If You are just looking for thew first occurrence, the pattern will be /[0-9]+/ - which will return 10

(There is no need for JQuery)

You can use regexp as explained by w3schools. Hint:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!