0

I'm trying to find if a given string of digits contains a sequence of three identical digits.

using a for loop, each digit in the string gets its own representation of a three digit sequence which is then checked against the string using Regex:

var str = "6854777322"

for(var i=0; i<str.length; i++)
{
   seqToCompare = str[i] + str[i] + str[i];
   var re = new RegExp(seqToCompare, "g");
   if(str.match(re).length == 1)
   {
      match = str[i];
   }
}
console.log(match)

The result should be seven (if I put 777 in seqToCompare, it would work), but it looks like the concatenation causes it to fail. Console shows "cannot read property length for null".

You can test it here - https://jsfiddle.net/kwnL7vLs/

I tried .toString, setting seqToCompare in Regex format and even parsing it as int (out of desperation for not knowing what to do anymore...)

2
  • If the match fails, the result is null and on the first iteration, the match does fail. Commented Nov 26, 2016 at 17:14
  • Thanks! I was sure it returned 0 rather than null because a comparison took place. Commented Nov 26, 2016 at 17:26

2 Answers 2

3

Rather than looping over each character, you can use a simple regex to get a digit that is repeated 3 times:

/(\d)(?=\1{2})/
  • (\d) - Here we match a digit and group it in captured group #1
  • (?=\1{2}) is lookahead that asserts same captured group #1 is repeated twice ahead of current position

RegEx Demo

Sign up to request clarification or add additional context in comments.

Comments

0

anubhava's answer is the way to go, as it's more efficient and simpler. However, if you're wondering why your code specifically is giving an error, it's because you try to find the length property of the return value of str.match(), even when no match is found.

Try this instead:

var str = "6854777322"

for(var i=0; i<str.length; i++)
{
   seqToCompare = str[i] + str[i] + str[i];
   var re = new RegExp(seqToCompare, "g");
   if(str.match(re))
   {
      match = str[i];
   }
}
console.log(match)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.