patternjavascriptMajor
Check if a string has 20 numbers in a row in it
Viewed 0 times
numbershasrowcheckstring
Problem
My code will check if the variable
Output:
myString has 20 running numbers.
myString has 20 running numbers. I'm new to JavaScript and I'm wondering if there is a simpler way to do this. How can I shorten my code and possibly make it more efficient?var myString = "tuxwuhkocx14789470019215498263ljmgwsxvne";
var runningNumbers = 0;
for (i = 0; i < myString.length; i++) {
var character = myString.charAt(i);
if (!isNaN(character)) {
// If character is a number:
runningNumbers = runningNumbers + 1;
} else {
// If character is NOT a number:
runningNumbers = 0;
}
if (runningNumbers == 20) {
console.log("myString has 20 running numbers.");
}
}Output:
myString has 20 running numbers.
Solution
If you use a regular expression to look for 20 digit characters (
You can shorten this further as just:
\d) in a row, then the code would be compact and the goal would be visible at a glance:var twentyDigits = /\d{20}/;
if (twentyDigits.test(myString)){
console.log("My string has 20 running numbers");
}You can shorten this further as just:
if (/\d{20}/.test(myString)) console.log("Yup. 20");Code Snippets
var twentyDigits = /\d{20}/;
if (twentyDigits.test(myString)){
console.log("My string has 20 running numbers");
}if (/\d{20}/.test(myString)) console.log("Yup. 20");Context
StackExchange Code Review Q#120374, answer score: 31
Revisions (0)
No revisions yet.