JavaScript Code Snippets
Explore and share JavaScript snippets for web development and scripting.
export function formatFileSize(bytes: number): string {
if (typeof bytes !== 'number' || isNaN(bytes) || bytes < 0) {
return 'Invalid size';
}
const units = ['bytes', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
while (bytes >= 1024 && i < units.length - 1) {
bytes /= 1024;
i++;
}
const value = i === 0 ? bytes : bytes.toFixed(2);
return `${value} ${units[i]}`;
}
// Example usage:
console.log(formatFileSize(500)); // 500 B
console.log(formatFileSize(1536)); // 1.50 KB
console.log(formatFileSize(1048576)); // 1.00 MB
console.log(formatFileSize(1073741824)); // 1.00 GB
console.log(formatFileSize()); // "Invalid size"
File size bytes to a human-readable format
Common Conversions (Binary - Base 2) – m...function sanitizeFilename(filename) {
// Remove the extension
const nameWithoutExt = filename.replace(/\.[^/.]+$/, '')
// Replace all non-alphanumeric characters with hyphens
const sanitized = nameWithoutExt.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '')
return sanitized
}
// Example usage
const input = "Mahbub-hasan.Hira.jpg";
const result = sanitizeFilename(input);
console.log(result); // Output: Mahbub-hasan-Hira
Get the filename without extension
1. firstly we remove the extension by r...const generateUsername = email =>
email.split('@')[0].replace(/[^a-zA-Z0-9]/g, '') + '_' + Math.random().toString(36).slice(2, 6);
// Example
console.log(generateUsername('john.doe@example.com')); // output ==> johndoe_ab3x
Generate a unique username from email
How it works: 1. split('@')[0]: takes th...function getRandomColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
Generate Random Hex Color JS
Create a random color in hex format with...// Function to sanitize a slug for URLs
export const sanitizeSlug = (slug) => {
if (!slug) return "";
return slug
?.trim() // Trim whitespace from the beginning and end
.toLowerCase() // Convert to lowercase
.replace(/[^a-z0-9\s-]/g, "") // Remove special characters except spaces and hyphens
.replace(/\s+/g, "-") // Replace spaces with hyphens
.replace(/-+/g, "-"); // Replace multiple hyphens with a single hyphen
};