JSFiddle - React, Tailwind, and code Playground
by JamesPattison
HTML
<span id="el">lel</span>
TypeScript
class RegexValidator {
getRegexLength(regExp: string): number {
const str = regExp, length = str.length;
let stringLength = 0, c:string, index = 0;
while (index < length) {
c = str[index++];
switch (c) {
case "[":
index = str.indexOf(']')+1;
break;
case "{":
const rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(index));
if (rs !== null) {
index += rs[0].length;
stringLength += parseInt(rs[1], 10);
}
break;
case "?": //optional, assume no instances for ease
case "(":
case "^":
case "$":
case ")":
case "|":
case "*": //any number, assume 0 for ease
break;
case "\\":
if (str[index + 1] !== "+"
&& str[index + 1] !== "?"
&& str[index + 1] !== "*"
&& str[index + 1] !== "{") {
stringLength++;
}
index++;
break;
default:
console.log(c);
stringLength++;
break;
}
}
return stringLength;
}
isValid(pattern: string | RegExp, value: P360.Data.StringVariable): boolean {
const regExpStr = pattern instanceof RegExp ? pattern.source : pattern;
var length = this.getRegexLength(regExpStr);
$("#el").html(length);
return true;
}
}
var val = new RegexValidator()
val.isValid('^\\w{4}$', 'xxxx');