var regex = /\d+/g;
var string = "you can enter maximum 500 choices";
var matches = string.match(regex); // creates array from matches
document.write(matches);
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
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);
// 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);`
findNumber = str => {
return +(str.replace(/\D+/g, ''));
}
console.log(findNumber("you can enter maximum 500 choices"));
console.log(findNumber("you can enter maximum 12500 choices"));
9条答案
按热度按时间t9eec4r01#
使用regular expression。
表达式
\d+
表示“一个或多个数字”。正则表达式默认为greedy,表示它们将尽可能多地获取。此外,还有:相当于:
请参见details for the RegExp object。
上面的代码将获取第一个组数字。你也可以循环查找所有匹配项:
g
(全局)标志是此循环工作的关键。njthzxwz2#
regular-expressions.info/javascript.html(archive)
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp(archive)
jgwigjjp3#
Playground:https://regex101.com/r/1ADa3c/1
fzsnzjdm4#
我喜欢@jesterjunk回答,然而,数字并不总是数字。考虑那些有效的数字:“123.5、123,567.789、12233234+第12款”
所以我更新了正则表达式:
brtdzjyr5#
我想我应该加上我的看法,因为我只对第一个整数感兴趣,我把它归结为:
.toString()
仅在从获取错误中获取“string”时添加。如果没有,则可以将其从行中删除。nr9pn0ug6#
fivyi3re7#
你也可以试试这个:
t0ybt7op8#
输出将为15
如果你想了解更多关于regex这里有一些链接:
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
aydmsdu99#
现在,使用***'replace'方法和'regexp'***很容易做到。