要從String
獲得所有數字,您可以使用\d+
。因此可以用一個while
循環的結果添加到一個數組,並獲得它們的最小/最大值:
實施例1個 - 使用函數
var min;
var max;
var text = "Being under 18 may require parental signature. "
+ "You must be at least 16 years in older to apply";
function getMinAndMax(string){
var p = RegExp("\\d+", "g"),
match, results = [];
while (match = p.exec(string))
results.push(match[0]); // [18, 16]
return [Math.min.apply(null, results), // 16
Math.max.apply(null, results)]; // 18
}
var ages = getMinAndMax(text); // [16, 18]
console.log("Min: " + ages[0]);
console.log("Max: " + ages[1]);
https://jsfiddle.net/oro4djpq/
實施例2 - 直銷
var p = RegExp("\\d+", "g"),
text = "Life Span: 10 to 12 years",
match, results = [];
while (match = p.exec(text))
results.push(match[0]); // [10, 12]
console.log("Min: " + Math.min.apply(null, results)); // [10]
console.log("Max: " + Math.max.apply(null, results)); // [12]
https://jsfiddle.net/rzo31teb/