Regular Expression Maximum Number Of Characters Javascript [duplicate]

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

Answers:

Answer

You can use a lookahead:

var regex = /^(?=.{0,6}$)[\S]+\-[\S]+$/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.