简体   繁体   English

如何在JavaScript的String中存在的变量中标识和存储数字?

[英]how to identify and store number in variables present in String in JavaScript?

let's say i have a string in format like 假设我有一个格式如下的字符串
1." Amount is between 5000 and 10000 " 1.“ Amount is between 5000 and 10000
2. " Amountbetween5000 and10000 " 2.“ Amountbetween5000 and10000
3." 5000 Amountbetweenand10000 " 3.“ 5000 Amountbetweenand10000
4." 50001000 amount " 4.“ 50001000 amount

then i need to store 5000 and 10000 in 2 variables let's say a and b 那么我需要将5000和10000存储在2个变量中,比如说a和b
if no number found then value of a and b will be 0 如果找不到数字,则a和b的值为0
string can or cannot have space between Words 字词之间可以有空格,也可以没有空格

You can use Regular Expressions 您可以使用正则表达式

var numbers = string.match(/\d+/g).map(Number);

\\d+ matches a digit (equal to [0-9]) \\d+匹配一个数字(等于[0-9])

+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) +量词-匹配一次和无限次,尽可能多地匹配,并根据需要返回(贪婪)

g modifier: global. g修饰符:全局。 All matches (don't return after first match) 所有比赛(第一次比赛后不返回)

Here in example, handled case if no match is found. 在此示例中,如果找不到匹配项,则处理情况。

 var string = "Amount is between 5000 and 10000", numbers = []; var arr = string.match(/\\d+/g); if (arr != null) numbers = arr.map(Number) console.log(numbers); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM