简体   繁体   中英

Test for n digits in a string

I am trying to solve 'JavaScript Algorithms and Data Structures Projects: Telephone Number Validator' @freeCodeCamp.

I need to test if string contains 10 digits and what I've come up with returns false and I don't understand why.

console.log(/\d{10}/g.test("555-555-5555"))

Here \\d{10} means ten consecutive digits , not "ten digits with whatever in the middle, that's cool".

If want just 10 digits, you may want to strip non-digit data first:

let number = "555-555-5555";

// Remove all non-digit values (\D) which leaves only digits
let digits = number.replace(/\D/g, '').length;

If you want to do this with a single regular expression, you can use:

 console.log(/^(?:\\D*\\d){10}\\D*$/g.test("555-555-5555")) console.log(/^(?:\\D*\\d){10}\\D*$/g.test("555-555-55555"))

requiring the input to be composed of exactly 10 digits in addition to any number of other non-digit characters - but replacing non-digits with the empty string first would be a more intuitive and readable solution.

It seems that your idea is correct, but this specific challenge has so many options for dashes [-] and parentheses [()] as inputs that there is a more efficient way to pass this.

function telephoneCheck(str) {
  let phoneRegex = /^(1\s?)?(\d{3}|\(\d{3}\))[\s\-]?\d{3}[\s\-]?\d{4}$/
  return phoneRegex.test(str);
}

The above is a way to complete the challenge in a single line of Regex, which can save you (or anyone else reading this in the future) a lot of time and space! Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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