2

So i have this regex:

var regex = /^[\S]+(\-[\S]+)$/

i want to add one more rule, the rule is that maximum number of characters is 6 or something, how do i do it? my full code looks like this

var regex = /^[\S]+(\-[\S]+)$/
var word = "a-a";

if(word.match(regex)){
    console.log("matched");
}else{
    console.log("did not match");
}
console.log(word.length);

i've tried var regex = /^([\S]+(\-[\S]+)){6}$/ but this means they must repeat a-a 6 times, i want the maximum number of characters, something like this:

var word = "123-56"

to be matched, how do i do it? and i don't want to use .length because i want to implement it into regex

nikagar4
  • 830
  • 4
  • 11
  • 23

1 Answers1

2

You can use a lookahead:

var regex = /^(?=.{0,6}$)[\S]+\-[\S]+$/
Adam
  • 4,985
  • 2
  • 29
  • 61