How to Convert Title or String to URL Slug Using JavaScript

Robin
Updated on April 30, 2023

For better Search Engine Optimization (SEO), your web pages or blog posts must have clean and optimized URLs. That's why your URL slugs should be simple and easy to read.

If your URL contains random numbers, symbols, or words that don't make any sense, it will negatively impact your website's search engine rankings.

But the good news is you can convert any title or string to a URL slug using JavaScript very easily. If you add this to your application, it will generate slugs for you automatically.

Today, you will learn the best way to transform any text into a simple, descriptive, and readable slug in JavaScript dynamically. This process will remove all the unnecessary things from your text before creating the slug.

What is a URL Slug?

A URL slug is the part of a URL that identifies a specific page or post on a website. It is the portion of the URL that comes after the domain name and any subdirectories.

A good slug should be short, easy to understand, and concise. It helps your readers to understand the content on the page. That's why a good URL slug also helps in search engine rankings.

For example, consider the URL of this blog post: "https://www.example.com/convert-title-to-url-slug-javascript/". In this URL, "convert-title-to-url-slug-javascript" is the slug.

Also Read: How to Capitalize the First Letter of Each Word in JavaScript


Convert Title or String to URL Slug in JavaScript

To generate a good slug from any string, you should follow some steps. This process will help you to create an optimized slug for your webpage.

These are the necessary steps for creating a URL slug in JavaScript:

  1. Convert the input to a string explicitly.
  2. Convert the string to lowercase letters.
  3. Remove any whitespaces from the beginning or end of the string.
  4. Replace any whitespace between words with the separator character.
  5. Remove any non-word characters (e.g., punctuation, symbols) from the string.
  6. Replace any underscores with the separator character.
  7. Replace multiple separator characters with a single separator.
  8. Remove any trailing separator character from the end.

Let's create a function will all these 8 steps. The purpose of the function is to accept a string as the parameter and convert it into a URL-friendly slug.

          const slugify = (string, separator = '-') => {
    return string
        .toString()    // Convert input to string (optional)
        .toLowerCase()    // Convert the string to lowercase letters
        .trim()    // Remove whitespace from both sides of the string
        .replace(/\s+/g, separator)    // Replace spaces with hyphen (-)
        .replace(/[^\w\-]+/g, '')    // Remove all non-word characters
        .replace(/\_/g, separator)    // Replace underscore (_) with hyphen (-)
        .replace(/\-\-+/g, separator)    // Replace multiple (-) with single (-)
        .replace(/\-$/g, '')    // Remove trailing (-)
}
        

This slugify() function takes 2 parameters. The first parameter is the text you want to slugify and the second parameter is the separator. By default, the separator is set to hyphen ( - ) if you don't provide any value.

Now apply those 8 steps on the string and return the slug from this slugify() function.

  1. string.toString(): This is optional, but it will ensure that the input is a string, in case you pass another data type.
  2. .toLowerCase(): This method converts the string to lowercase letters, which makes the slug easier to read and good for SEO.
  3. .trim(): It removes any whitespace from the beginning or end of the string, which is a good practice to ensure consistent formatting.
  4. .replace(/\s+/g, separator): This regular expression will replace any whitespace character between words with the separator character (which is "-" by default).
  5. .replace(/[^\w\-]+/g, ''): This regular expression will remove any non-word characters (e.g., punctuation, symbols) from the string.
  6. .replace(/\_/g, separator): This regular expression will replace any underscores with the separator character (e.g., "-" instead of "_").
  7. .replace(/\-\-+/g, separator): This regular expression will replace multiple instances of the separator character with a single instance (e.g., "--" becomes "-").
  8. .replace(/\-$/g, ''): This regular expression will remove any trailing separator character from the end of the URL slug.

Now call this function with a string and see the result.

          const title = 'Create Websites from Scratch with HTML, CSS, and JavaScript'

const slug = slugify(title)

console.log(slug)
// create-websites-from-scratch-with-html-css-and-javascript
        

As you can see, it works perfectly. It converts the characters to lowercase, removes all the non-word characters from the string, and adds a separator in between each word.

If you don't pass any separator to this function, it will use the hyphen ( - ) by default. But you can also use other separators like underscore ( _ ) if you want.

          const title = 'Create Websites from Scratch with HTML, CSS, and JavaScript'

const slug = slugify(title, '_')

console.log(slug)
// create_websites_from_scratch_with_html_css_and_javascript
        

But it is always recommended to use the hyphen ( - ) instead of the underscore ( _ ) in URLs. Because it is readable, user-friendly, and better for search engine optimization (SEO).

Also Read: How to Split Paragraphs into Sentences Using JavaScript


Conclusion

Many websites allow users to create their content. If every time they have to think and create their own URL slug, it will be a bad user experience.

That's why you should convert the titles or strings into URL slugs automatically for your users. As you can see, it is very easy to generate slugs using JavaScript.

If you follow those 8 steps to transform any text into a slug, you will get an SEO-friendly, clean, and descriptive slug for your URL. Your users will understand the type of content just by reading the URL slug.

Related Posts