0

I am trying to check whether an input meets a given format - using Regex.

  • Characters 1 to 4 of the input need to be digits (0-9).
  • Character 5 needs to be a dash (-).
  • Characters 6 to 8 also need to be digits (0-9).

Example:
1234-567 should be ok.

I have tried the following but I am a beginner regarding Regex and could not get this to work.

Can someone help me with this and also provide some explanations around it so that I can apply it correctly next time ?

My Code:

var str = '1234-567';
var allowedChars1 = /^(.{3})[0-9]/;
var allowedChars2 = /^.{4}(.{1})[\-]/;
var allowedChars3 = /^.{5}(.{3})[0-9]/;

if( (str.match(allowedChars1)) && (str.match(allowedChars2)) && (str.match(allowedChars3)) ) {
    console.log('ok');
} else {
    console.log('error');
}

Many thanks in advance, Tom

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
keewee279
  • 1,656
  • 5
  • 28
  • 60

0 Answers0