JavaScript Code Snippets

Explore and share JavaScript snippets for web development and scripting.

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
};

Slugify a String in Javascript

Convert a string into a clean URL-friend...