Nivi M
Nivi M

Reputation: 111

Javascript - Using Concatenated String in Regex

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...)

Upvotes: 0

Views: 54

Answers (2)

Eric Zhang
Eric Zhang

Reputation: 601

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)

Upvotes: 0

anubhava
anubhava

Reputation: 784958

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

Upvotes: 3

Related Questions