Home > Article > Web Front-end > Convert String Title to Slug in Javascript
To convert a title to a slug format using JavaScript, you need to transform the title into a URL-friendly string. This typically involves lowercasing the string, replacing spaces and other non-alphanumeric characters with hyphens, and removing any leading or trailing hyphens. Here is a step-by-step guide on how to achieve this:
Convert the string to lowercase: This ensures consistency in the slug format.
Here's a sample JavaScript function to do this:
function stringToSlug(title) { return title .toLowerCase() // Convert to lowercase .replace(/[^a-z0-9 -]/g, '') // Remove invalid characters .replace(/\s+/g, '-') // Replace spaces with hyphens .replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen .replace(/^-+|-+$/g, ''); // Remove leading and trailing hyphens } // Example usage: const title = "This is a Sample Title!"; const slug = stringToSlug(title); console.log(slug); // Output: "this-is-a-sample-title"
Explanation:
This function will help you convert any title string into a clean, URL-friendly slug.
The above is the detailed content of Convert String Title to Slug in Javascript. For more information, please follow other related articles on the PHP Chinese website!