如何使用JavaScript在字符串中查找数字? [英] How to find a number in a string using JavaScript?

查看:108
本文介绍了如何使用JavaScript在字符串中查找数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串 - 你可以输入最多500个选项。
我需要从字符串中提取 500

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

主要问题是String可能会有所变化你可以输入最多12500个选择。
那么如何获得整数部分?

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

推荐答案

使用正则表达式

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

表达式 \d + 表示一个或更多数字。默认情况下,正则表达式是贪婪,这意味着他们会尽可能多地抓住它们。另外,这个:

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+/;

相当于:

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

请参阅 RegExp对象的详细信息

以上将抓住第一个一组数字。您也可以循环查找所有匹配项:

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]);
}

g ( global)标志是这个循环工作的关键。

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

这篇关于如何使用JavaScript在字符串中查找数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆