CrackStack1
CrackStack1

Reputation: 19

Javascript: using Regex to search for any four digits in a row

I am trying to create a function that confirms if a string contains any four digits in a row (for the purposes of finding a date).

The code I have is:

string.search(^\d{4}$)

Any advice? I'm really inexperienced with Regex. I'd also appreciate any input on where to learn to use Regex more effectively.

Upvotes: 1

Views: 895

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382112

What you want is

/\d{4}/.test(yourString)

which returns a boolean.

Note that

  • the ^ and $ you were using match the start and end of the string. They would have been useful to test if a string was only made of 4 digits.
  • search is useful when you want the position of the match. In your case test is simpler.

To go further, I recommend this good and concise documentation on regexes in JavaScript

Upvotes: 5

Related Questions