JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="input" rows="10" cols="100" placeholder="Input regex"></textarea>
<br>
<input id="removeComments" type="checkbox" checked>Remove comments<br>
<input id="removeNewLines" type="checkbox" checked>Remove new lines<br>
<input id="removeUnescapedSpaces" type="checkbox" checked>Remove unescaped spaces<br>
<input id="substituteNamedGroups" type="checkbox" checked>Substitute named groups<br>
<input type="button" value="Process" onclick="processRegex()"><br>
<textarea id="output" rows="10" cols="100" placeholder="Output regex"></textarea>
<br>
JavaScript
function processRegex()
{
var regex = document.getElementById("input").value;
if (document.getElementById("removeComments").checked) {
regex = regex.replace(/#(.*?)\n/gm, "\n");
}
if (document.getElementById("removeNewLines").checked) {
regex = regex.replace(/\n/gm, "");
}
if (document.getElementById("removeUnescapedSpaces").checked) {
regex = removeUnescapedSpaces(regex);
}
if (document.getElementById("substituteNamedGroups").checked) {
regex = handleNamedGroups(regex);
}
document.getElementById("output").value = regex;
}
function handleNamedGroups(regex)
{
var start = 0;
var end = 0;
var namedGroups = {};
// populate `namedGroups` hashtable with groupname=group entries
while (1) {
start = regex.indexOf("(?<", start);
end = regex.indexOf(">", start + 3);
if (start == -1 || end == -1) {
break;
}
// make sure that the group name starts with a letter
// so that we don't match lookbehinds (?<=)
if (!regex.charAt(start + 3).match(/[a-z]/i)) {
start ++;
continue;
}
var name = regex.substring(start + 3, end);
var endParen = findIndexOfMatchingClosingParen(regex, end);
namedGroups[name] = "(" + regex.substring(end + 1, endParen + 1);
start = end;
}
// go over each entry in hashtable and replace key with the value in the `regex`
for (var key in namedGroups) {
regex = regex.replace(new RegExp("\\\\g\\<" + key + "\\>", "gmi"), namedGroups[key]);
}
return regex;
}
function findIndexOfMatchingClosingParen(str, openParenIndex)
{
var count = 1;
for (var i = openParenIndex + 1; i < str.length; i ++) {
if (str.charAt(i) == ')') {
count --;
} else if (str.charAt(i) == '(') {
count ++;
...