gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
html css js url shortener database "#/"
- User
html css js url shortener database "#/"
- Assistant
html css js url shortener database "#/"
Certainly! Here's a simple example of a URL shortener built with HTML, CSS, and JavaScript. It uses the browser's localStorage as a simple database to store short URLs and their corresponding original URLs. It also supports URL fragment identifier #/ for routing.
#/shortcode, it redirects you to the original URL#/abc123, it will look up abc123 in localStorage and redirect.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Simple URL Shortener</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
background: #f0f0f0;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
}
#shorten-form {
max-width: 500px;
margin: 0 auto 20px;
display: flex;
gap: 10px;
}
input[type="url"] {
flex-grow: 1;
padding: 10px;
font-size: 1rem;
}
button {
padding: 10px 15px;
font-size: 1rem;
cursor: pointer;
}
#message {
text-align: center;
margin-bottom: 15px;
color: green;
}
#error {
text-align: center;
margin-bottom: 15px;
color: red;
}
#list {
max-width: 600px;
margin: 0 auto;
background: #fff;
border-radius: 6px;
padding: 10px;
}
#list h2 {
margin-top: 0;
}
.entry {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #ddd;
padding: 6px 0;
}
.entry:last-child {
border-bottom: none;
}
.urls {
flex-grow: 1;
margin-right: 10px;
word-break: break-all;
}
button.copy-btn,
button.delete-btn {
margin-left: 5px;
padding: 5px 8px;
font-size: 0.9rem;
}
a.short-link {
color: #007acc;
text-decoration: none;
}
a.short-link:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Simple URL Shortener</h1>
<div id="content">
<form id="shorten-form">
<input type="url" id="url-input" placeholder="Enter URL to shorten" required />
<button type="submit">Shorten</button>
</form>
<div id="message"></div>
<div id="error"></div>
<div id="list">
<h2>Your Shortened URLs</h2>
<div id="urls-list"></div>
</div>
</div>
<script>
// Use location origin + /#/code as short URL base
const baseUrl = window.location.origin + "/#/";
// Load short URLs from localStorage
function loadUrls() {
let data = localStorage.getItem("urlShortenerData");
return data ? JSON.parse(data) : {};
}
// Save short URLs to localStorage
function saveUrls(urls) {
localStorage.setItem("urlShortenerData", JSON.stringify(urls));
}
// Generate a random 6 char string as shortcode
function generateCode(length = 6) {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let result = "";
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
// Validate URL (simple)
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
function displayMessage(msg, isError = false) {
const msgDiv = document.getElementById("message");
const errDiv = document.getElementById("error");
if (isError) {
errDiv.textContent = msg;
msgDiv.textContent = "";
} else {
msgDiv.textContent = msg;
errDiv.textContent = "";
}
}
// Render the list of shortened URLs
function renderList() {
const urlsList = document.getElementById("urls-list");
urlsList.innerHTML = "";
const urls = loadUrls();
const entries = Object.entries(urls);
if (!entries.length) {
urlsList.textContent = "No URLs shortened yet.";
return;
}
entries.forEach(([code, longUrl]) => {
const div = document.createElement("div");
div.className = "entry";
const urlsDiv = document.createElement("div");
urlsDiv.className = "urls";
const shortLink = document.createElement("a");
shortLink.href = baseUrl + code;
shortLink.target = "_blank";
shortLink.rel = "noopener";
shortLink.textContent = baseUrl + code;
shortLink.className = "short-link";
const longLink = document.createElement("div");
longLink.textContent = longUrl;
urlsDiv.appendChild(shortLink);
urlsDiv.appendChild(document.createElement("br"));
urlsDiv.appendChild(longLink);
div.appendChild(urlsDiv);
// Copy button
const copyBtn = document.createElement("button");
copyBtn.textContent = "Copy";
copyBtn.className = "copy-btn";
copyBtn.onclick = () => {
navigator.clipboard.writeText(baseUrl + code).then(() => {
displayMessage("Copied to clipboard!");
setTimeout(() => displayMessage(""), 2000);
});
};
div.appendChild(copyBtn);
// Delete button
const deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.className = "delete-btn";
deleteBtn.onclick = () => {
if (confirm("Delete this shortened URL?")) {
let urls = loadUrls();
delete urls[code];
saveUrls(urls);
renderList();
displayMessage("Deleted!");
}
};
div.appendChild(deleteBtn);
urlsList.appendChild(div);
});
}
// Handle form submission
document.getElementById("shorten-form").addEventListener("submit", e => {
e.preventDefault();
const urlInput = document.getElementById("url-input");
const longUrl = urlInput.value.trim();
if (!isValidUrl(longUrl)) {
displayMessage("Invalid URL! Please enter a valid URL starting with http(s)://", true);
return;
}
let urls = loadUrls();
// Check if URL already shortened
for (const [code, url] of Object.entries(urls)) {
if (url === longUrl) {
displayMessage(`URL already shortened: ${baseUrl}${code}`);
urlInput.value = "";
renderList();
return;
}
}
// Generate unique code
let code;
do {
code = generateCode();
} while (urls.hasOwnProperty(code));
urls[code] = longUrl;
saveUrls(urls);
displayMessage(`Shortened URL: ${baseUrl}${code}`);
urlInput.value = "";
renderList();
});
// On page load, check for hash in URL to redirect
function checkRedirect() {
const hash = window.location.hash || "";
if (hash.startsWith("#/")) {
const code = hash.slice(2);
if (code) {
const urls = loadUrls();
const longUrl = urls[code];
if (longUrl) {
// Redirect
window.location.href = longUrl;
} else {
// Invalid code
document.getElementById("content").innerHTML =
`<h2>Invalid short URL: ${code}</h2>
<p><a href="${window.location.origin}">Go back</a></p>`;
}
return true;
}
}
return false;
}
// Start
if (!checkRedirect()) {
renderList();
}
</script>
</body>
</html>
index.html.origin/#/code.Note:
This is a front-end only demo. For a real URL shortener, you'd want a backend server with a database to store URLs and handle redirects securely. This example uses localStorage and is only accessible on the client side.
If you want me to help integrate this with a backend and a database (Node.js + Express + MongoDB, for example), just ask!
Not yet included in a published release.