Javascript regex pattern to match for Function keys from F1-F12 using pattern test function
I tried below but gives false as output, excepted is true
let text = "F11";
let pattern = /^[F][1-12]$/;
let result = pattern.test(text); console.log(result);
CodePudding user response:
This regular expression matches F1-F12: /^F[1-9](?:(?<=1)(?:0|1|2))?$/
:
let re = /^F[1-9](?:(?<=1)(?:0|1|2))?$/;
for (var i = 0; i < 16; i ){
let text = `F${i}`;
console.log(`${text}: ${re.test(text)}`);
}
To break it down:
^
matches the start of input; it will only match if it is at the beginningF
matches a literal'F'
[1-9]
matches a character between 1 and 9(?:(?<=1)(?:0|1|2))
is where it matches 11 and 12(?<=1)(?:0|1|2))
is a lookbehind assertion: it will only match the second part if the first is true(?:0|1|2)
matches the 0, 1, or 2 for the 10-12