url-notes-extractor / script.js
laredoj's picture
Location and name should be extracted from the URL, Notes should be optional
52375dd verified
document.addEventListener('DOMContentLoaded', function() {
const urlInput = document.getElementById('url-input');
const extractBtn = document.getElementById('extract-btn');
const locationElement = document.getElementById('location');
const nameElement = document.getElementById('name');
const notesElement = document.getElementById('notes');
const notesInput = document.getElementById('notes-input');
const saveNotesBtn = document.getElementById('save-notes-btn');
// Extract data from URL
extractBtn.addEventListener('click', function() {
const url = urlInput.value.trim();
if (!url) {
alert('Please enter a URL');
return;
}
try {
const urlObj = new URL(url);
const pathSegments = urlObj.pathname.split('/').filter(segment => segment);
// Extract location and name from path
if (pathSegments.length >= 2) {
locationElement.textContent = decodeURIComponent(pathSegments[pathSegments.length - 2]);
nameElement.textContent = decodeURIComponent(pathSegments[pathSegments.length - 1]);
} else if (pathSegments.length === 1) {
locationElement.textContent = '-';
nameElement.textContent = decodeURIComponent(pathSegments[0]);
} else {
locationElement.textContent = '-';
nameElement.textContent = '-';
}
// Extract notes from query params
const notes = urlObj.searchParams.get('notes');
if (notes) {
notesElement.textContent = decodeURIComponent(notes);
notesInput.value = decodeURIComponent(notes);
} else {
notesElement.textContent = '-';
notesInput.value = '';
}
} catch (error) {
alert('Invalid URL format');
console.error(error);
}
});
// Save notes to URL
saveNotesBtn.addEventListener('click', function() {
const url = urlInput.value.trim();
if (!url) {
alert('Please enter a URL first');
return;
}
try {
const urlObj = new URL(url);
const notes = notesInput.value.trim();
if (notes) {
urlObj.searchParams.set('notes', encodeURIComponent(notes));
notesElement.textContent = notes;
} else {
urlObj.searchParams.delete('notes');
notesElement.textContent = '-';
}
urlInput.value = urlObj.toString();
} catch (error) {
alert('Error updating URL');
console.error(error);
}
});
// Example URL on page load for demonstration
urlInput.value = 'https://example.com/new-york/central-park?notes=beautiful-park';
});