Regex Pattern Tester & Code Snippet
1. Enter Text & Pattern
2. Match Visualization (Editable)
Run the test first.
3. Code Snippet (Editable)
Please enter a pattern.
`; dashboardResults.value = ""; return; } let regex; try { // Create RegExp object regex = new RegExp(patternString, flags); } catch (e) { highlightedOutput.innerHTML = `Invalid Regex Pattern: ${e.message}
`; dashboardResults.value = ""; return; } // --- 1. Find Matches --- const matches = text.match(regex) || []; dashboardResults.value = matches.join('\n'); // --- 2. Highlight Text --- let highlightedHtml = text; if (matches.length > 0) { // Need to use the global flag 'g' for replace to catch all instances const replaceRegex = new RegExp(patternString, (flags.includes('g') ? flags : flags + 'g')); highlightedHtml = text.replace(replaceRegex, (match) => { // Use a temporary non-breaking character placeholder to keep the HTML safe return `${match}`; }); highlightedHtml = `${highlightedHtml}`; // Use to preserve whitespace/line breaks
} else {
highlightedHtml = `No matches found.
`;
}
highlightedOutput.innerHTML = highlightedHtml;
// --- 3. Generate Code Snippet ---
const code = generateCodeSnippet(patternString, flags, matches);
dashboardCode.value = code;
showTab("rpt-tab-dashboard");
}
/**
* Generates the JavaScript code snippet
*/
function generateCodeSnippet(pattern, flags, matches) {
const escapedPattern = pattern.replace(/\\/g, '\\\\').replace(/\//g, '\\/'); // Escape backslashes and slashes for string literal
const matchesArray = matches.map(m => ` "${m}"`).join(',\n');
return `
// Input text
const textToSearch = \`
${configTextarea.value}
\`;
// Regular Expression
const pattern = /${patternString}/${flags};
// Method 1: Find all matches (returns an array of matched strings)
const matches = textToSearch.match(pattern);
// Result:
/*
[
${matchesArray}
]
*/
// Method 2: Replace matches (Example: replace emails with [REDACTED])
// const redactedText = textToSearch.replace(pattern, "[REDACTED]");
// Method 3: Test for existence
// const found = pattern.test(textToSearch);
`.trim();
}
/**
* Generates a PDF report from the dashboard data
*/
function downloadPDF() {
if (typeof window.jspdf === 'undefined') {
alert("Error: PDF library (jsPDF) could not be loaded. Please try again.");
return;
}
// Get potentially edited values from dashboard
const pattern = configPattern.value || "/[No Pattern]/";
const flags = getFlags();
const textToSearch = configTextarea.value || "[No Sample Text]";
const rawMatches = dashboardResults.value || "No matches found.";
const codeSnippet = dashboardCode.value || "// No code snippet generated.";
const { jsPDF } = window.jspdf;
const doc = new jsPDF("p", "pt", "a4");
const margin = 40;
let yPos = margin;
const lineHeight = 16;
const usableWidth = doc.internal.pageSize.getWidth() - margin * 2;
doc.setFontSize(18);
doc.setFont(undefined, 'bold');
doc.text("Regex Test Results & Snippet", margin, yPos);
yPos += 30;
// --- Pattern & Flags ---
doc.setFontSize(14);
doc.text("Pattern:", margin, yPos);
doc.setFont('courier', 'normal');
doc.setFontSize(12);
doc.text(`/${pattern}/${flags}`, margin + 60, yPos);
yPos += lineHeight * 1.5;
// --- Sample Text ---
doc.setFontSize(14);
doc.setFont(undefined, 'bold');
doc.text("Sample Text:", margin, yPos);
yPos += lineHeight * 1.2;
doc.setFontSize(10);
doc.setFont('courier', 'normal');
const textLines = doc.splitTextToSize(textToSearch, usableWidth);
doc.text(textLines, margin, yPos);
yPos += textLines.length * lineHeight + 10;
// --- Raw Matches ---
if (yPos > doc.internal.pageSize.getHeight() - 100) { doc.addPage(); yPos = margin; }
doc.setFontSize(14);
doc.setFont('helvetica', 'bold');
doc.text("Raw Matches Found:", margin, yPos);
yPos += lineHeight * 1.2;
doc.setFontSize(10);
doc.setFont('courier', 'normal');
const matchLines = doc.splitTextToSize(rawMatches, usableWidth);
doc.text(matchLines, margin, yPos);
yPos += matchLines.length * lineHeight + 10;
// --- Code Snippet ---
if (yPos > doc.internal.pageSize.getHeight() - 150) { doc.addPage(); yPos = margin; }
doc.setFontSize(14);
doc.setFont('helvetica', 'bold');
doc.text("JavaScript Code Snippet:", margin, yPos);
yPos += lineHeight * 1.2;
doc.setFontSize(9);
doc.setFont('courier', 'normal');
const codeLines = doc.splitTextToSize(codeSnippet, usableWidth);
doc.text(codeLines, margin, yPos);
doc.save("Regex_Test_Results.pdf");
}
/**
* Helper to escape HTML
*/
function escapeHTML(str) {
if (!str) return "";
return str
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// --- 4. INITIALIZATION & EVENT LISTENERS ---
// Tab Listeners
tabButtons.forEach((btn) => {
btn.addEventListener("click", () => showTab(btn.dataset.target));
});
navButtons.forEach((btn) => {
btn.addEventListener("click", () => showTab(btn.dataset.target));
});
// Config Tab Listeners
if (testBtn) {
testBtn.addEventListener("click", handleTestPattern);
}
// Dashboard Tab Listeners
if (pdfBtn) {
pdfBtn.addEventListener("click", downloadPDF);
}
// Set initial sample text
configTextarea.value = "Project Alpha is scheduled for 2026/05/15. My email is user@domain.org. Your file is named file-123.pdf.";
// Initial State (default to config tab)
showTab("rpt-tab-config");
});
