Title description (Source: Niuke.com)
Given the string str, check whether it contains 3 consecutive numbers
1. If included, return the string of the latest 3 digits.
2. If not included, return false
Example 1
Enter
'9876543'
Output
987
Solution 1: This method is very stupid, it is the kind that can be understood at a glance.
Code:
function captureThreeNumbers(str) {
arr = str.split('');
var l=arr.length;
for(var i=0;i<l-2;i++){
if(Number(arr[i]) && Number(arr[i+1]) && Number(arr[i+2])){
var f = str.substr(i,3);
return f;
}
}
return false;
}
Solution 2: The first reaction most people see this is regular expressions.
Code:
function captureThreeNumbers(str) {
var result =/\d{3}/.exec(str);
if(result) {
return result[0];
} else {
return false;
}
}
In addition, there is a pitfall in this question, that is, the question is just to check whether there are 3 consecutive numbers in the string , instead of 3 consecutive numbers . I think many people have been pitted, so if it is three For continuous numbers, I don’t know how to write it with regular expressions, but I still use this stupid method. If you know a simpler method:
function captureThreeNumbers(str) {
for(var i = 0; i < str.length - 2; i++) {
if(str[i] >= '0' && str[i] <= '9') {
if(Math.abs(str[i] - str[i+1]) === 1 && Math.abs(str[i+1] - str[i+2]) === 1) {
return str.substr(i, 3)
}
}
}
return false;
}