Home > Web Front-end > JS Tutorial > body text

Convert String Title to Slug in Javascript

王林
Release: 2024-07-27 20:58:12
Original
759 people have browsed it

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.

  1. Replace spaces and non-alphanumeric characters with hyphens: 2. This makes the string URL-friendly.
  2. Remove leading and trailing hyphens: Clean up any extra hyphens added at the start or end of the string.

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"
Copy after login

Explanation:

  1. toLowerCase(): Converts the entire string to lowercase.
  2. replace(/[^a-z0-9 -]/g, ''): Removes any characters that are not lowercase letters, numbers, spaces, or hyphens.
  3. replace(/s+/g, '-'): Replaces one or more spaces with a 4. single hyphen.
  4. replace(/-+/g, '-'): Replaces multiple consecutive hyphens with a single hyphen.
  5. replace(/^-+|-+$/g, ''): Removes leading and trailing hyphens.

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!