JSFiddle - React, Tailwind, and code Playground
JavaScript
// Enumeration for specifying the type of pattern
PatternType = {
PREFIX : 0,
SUFFIX : 1,
ALL : 2
};
// Escape one or more characters within a character class
function escapeCharClass(string) {
// The only characters in a character class that need to be escaped are the
// backslash (\), the caret (^), and the hyphen (-).
// See http://www.regular-expressions.info/charclass.html
return string.replace(/([\\\^\-])/g, "\\$1");
}
// Find out whether the supplied suffixes or prefixes intersect
function fixesIntersect(string1, string2, patternType) {
var regexstr = "";
var inCharClass = false;
var charClass = "";
// Build up a regular expression for string1
for (var charPos = 0; charPos < string1.length; charPos++) {
var chr = string1.charAt(charPos);
// Build expression differently depending on whether the current character
// is within a character class
if (inCharClass) {
if (chr == ']') {
charClass = escapeCharClass(charClass);
regexstr += "([" + charClass + "?]|\\[[^\\]]*[" + charClass + "].*?\\])";
charClass = "";
inCharClass = false;
} else {
charClass += chr;
}
} else {
if (chr == '[') {
inCharClass = true;
} else if (chr == '?') {
regexstr += "(\\[.*?\\]|[^\\]])";
} else if (chr == '*') {
regexstr += "(\\[.*?\\]|[^\\]])*";
} else {
regexstr += "([" + escapeCharClass(chr) + "?]|\\[[^\\]]*[" + escapeCharClass(chr) + "].*?\\])";
}
}
}
if (inCharClass) {
alert("ERROR: Unterminated character class in pattern: " + string1);
throw "";
}
switch (patternType)
{
case PatternType.PREFIX:
// Prefix must be at the start - the ^ regex character denotes this
...