DEV Community

Query Filter
Query Filter

Posted on

form3

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Offline SQL Formatter</title>
<style>
  body { font-family: sans-serif; margin: 20px; }
  textarea { width: 100%; height: 200px; margin-bottom: 10px; font-family: monospace; }
  button { padding: 10px 20px; font-size: 16px; }
</style>
</head>
<body>

<h2>Offline SQL Formatter</h2>

<textarea id="input" placeholder="Paste your SQL here"></textarea><br>
<button id="formatBtn">Format SQL</button><br>
<textarea id="output" placeholder="Formatted SQL will appear here"></textarea>

<script>
// Improved offline SQL formatter
function formatSQL(sql) {
  if (!sql) return "";
  // Normalize spaces
  sql = sql.replace(/\s+/g, " ").trim();
  const keywords = [
    "SELECT","FROM","WHERE","GROUP BY","ORDER BY","HAVING",
    "INSERT INTO","VALUES","UPDATE","SET","DELETE","JOIN","INNER JOIN",
    "LEFT JOIN","RIGHT JOIN","ON","AND","OR"
  ];

  // Add line breaks before keywords
  keywords.forEach(k => {
    const re = new RegExp("\\b" + k + "\\b","gi");
    sql = sql.replace(re, "\n" + k);
  });

  // Split into lines and indent
  const lines = sql.split("\n").map(line => line.trim()).filter(line=>line);
  let indent = 0;
  const indentKeywords = ["SELECT","FROM","WHERE","GROUP BY","ORDER BY","HAVING","SET","VALUES","ON"];
  const subIndentKeywords = ["AND","OR","JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN"];
  const formatted = lines.map(line => {
    let ind = "";
    if (subIndentKeywords.some(k=>line.toUpperCase().startsWith(k))) ind = "    ".repeat(indent+1);
    else ind = "    ".repeat(indent);

    if (indentKeywords.includes(line.toUpperCase().split(" ")[0])) indent = 1;
    return ind + line;
  });
  return formatted.join("\n");
}

document.getElementById("formatBtn").addEventListener("click", () => {
  const sql = document.getElementById("input").value;
  const formatted = formatSQL(sql);
  document.getElementById("output").value = formatted;
});
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)