最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Reject phone number with all same digits in javascript? - Stack Overflow

programmeradmin1浏览0评论

I am looking to reject phone numbers that have all the same digits.

Example: 222-222-2222 or 333-333-3333

I tried stupidly looping through all the characters, but that was a bad idea.

I am looking to reject phone numbers that have all the same digits.

Example: 222-222-2222 or 333-333-3333

I tried stupidly looping through all the characters, but that was a bad idea.

Share Improve this question asked Apr 24, 2014 at 14:42 JohnstonJohnston 20.9k22 gold badges75 silver badges124 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

To test if a string contains only one distinct digit character (plus potentially arbitrary many non-digit characters), you can use:

function areAllDigitsTheSame(phoneNumber) {
    return /^\D*(\d)(?:\D*|\1)*$/.test(phoneNumber);
}

To test if a string matches the exact pattern ###-###-#### with all digits being the same, you can use:

function areAllDigitsTheSame(phoneNumber) {
    return /^(\d)\1\1-\1\1\1-\1\1\1\1$/.test(phoneNumber);
}

In both cases, the key point is that the () notation in a regex "captures" what it matches and makes it available for a back-reference (\1) to specify that it matches only an identical substring.

You can use this regex:

^(?!(\d)\1+(?:-\1+){2}$)\d+(-\d+){2}$

Online Demo

If you want to match the exact pattern

var str = '222-222-2222';
allowed(str); // false, console log bad

var str = '123-456-7890';
allowed(str); // true, console log good

function allowed(n) {

  if (/(\d)\1{2}-\1{3}-\1{4}/.test(n)) { console.log('bad'); return false; }
  console.log('good');
  return true;
} 

Here is the fiddle

Good luck :)

You can do this:

function AllSameDigits(str) {
    return /^(\d)\1+$/.test(str.replace(/[^\d]/g,''));
}

str='222-222-2222';
alert(AllSameDigits(str));

This strips out all non-digit characters, then asks: does the string start with a digit and consist of only the same digit repeated some number of times?

you need to first remove the hiphens and then check your number with this :

^(\d)\1+$

demo here : http://regex101./r/iJ2aB0

发布评论

评论列表(0)

  1. 暂无评论