JAVASCRIPT

Sanitize String by Removing Special Characters

Clean strings by removing special characters, punctuation, and converting to a web-friendly slug format using a JavaScript regex for URLs or filenames.

function sanitizeAndSlugify(text) {
  // Convert to lowercase
  text = text.toLowerCase();
  // Replace spaces with hyphens
  text = text.replace(/\s+/g, '-');
  // Remove all non-alphanumeric (and non-hyphen) characters
  text = text.replace(/[^a-z0-9-]/g, '');
  // Replace multiple hyphens with a single one
  text = text.replace(/--+/g, '-');
  // Trim hyphens from start/end
  text = text.replace(/^-+|-+$/g, '');
  
  return text;
}

// Example usage:
console.log(sanitizeAndSlugify("My Article Title! 123_test")); // "my-article-title-123-test"
console.log(sanitizeAndSlugify("  Another Title with Spaces & Symbols  ")); // "another-title-with-spaces-symbols"
How it works: This JavaScript function takes a string and sanitizes it by removing special characters and formatting it into a web-friendly 'slug'. It converts the text to lowercase, replaces spaces with hyphens, removes all characters that are not alphanumeric or hyphens, collapses multiple hyphens, and finally trims leading/trailing hyphens. This is commonly used to generate clean URLs, filenames, or unique identifiers from user-provided titles.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs