How to find a number in a string using JavaScript?

2020-01-24 07:55发布

Suppose I have a string like - "you can enter maximum 500 choices". I need to extract 500 from the string.

The main problem is the String may vary like "you can enter maximum 12500 choices". So how to get the integer part?

7条回答
唯我独甜
2楼-- · 2020-01-24 08:21

I like @jesterjunk answer, however, a number is not always just digits. Consider those valid numbers: "123.5, 123,567.789, 12233234+E12"

So I just updated the regular expression:

var regex = /[\d|,|.|e|E|\+]+/g;

var string = "you can enter maximum 5,123.6 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches); //5,123.6
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-24 08:23

var regex = /\d+/g;
var string = "you can enter 30%-20% maximum 500 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches);

查看更多
ら.Afraid
4楼-- · 2020-01-24 08:26

You can also try this :

var string = "border-radius:10px 20px 30px 40px";
var numbers = string.match(/\d+/g).map(Number);
console.log(numbers)

查看更多
疯言疯语
5楼-- · 2020-01-24 08:27
// stringValue can be anything in which present any number
`const stringValue = 'last_15_days';
// /\d+/g is regex which is used for matching number in string
// match helps to find result according to regex from string and return match value
 const result = stringValue.match(/\d+/g);
 console.log(result);`

output will be 15

If You want to learn more about regex here are some links:

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://www.tutorialspoint.com/javascript/javascript_regexp_object.htm

查看更多
够拽才男人
6楼-- · 2020-01-24 08:30
var str = "you can enter maximum 500 choices";
str.replace(/[^0-9]/g, "");
console.log(str); // "500"
查看更多
7楼-- · 2020-01-24 08:37

Use a regular expression.

var r = /\d+/;
var s = "you can enter maximum 500 choices";
alert (s.match(r));

The expression \d+ means "one or more digits". Regular expressions by default are greedy meaning they'll grab as much as they can. Also, this:

var r = /\d+/;

is equivalent to:

var r = new RegExp("\d+");

See the details for the RegExp object.

The above will grab the first group of digits. You can loop through and find all matches too:

var r = /\d+/g;
var s = "you can enter 333 maximum 500 choices";
var m;
while ((m = r.exec(s)) != null) {
  alert(m[0]);
}

The g (global) flag is key for this loop to work.

查看更多
登录 后发表回答