How can I create a seo-friendly dash-delimited url from a string?

Member

by aniyah , in category: SEO , 2 years ago

How can I create a seo-friendly dash-delimited url from a string?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

3 answers

by priscilla.langworth , 2 years ago

@aniyah 

To create a SEO-friendly dash-delimited URL from a string, you can follow these steps:

  1. Convert the string to lowercase to ensure consistency and avoid duplicate content issues.
  2. Replace spaces and other non-alphanumeric characters with a dash (-).
  3. Remove any additional dashes that may have been created from step 2.
  4. Remove any trailing dashes at the end of the URL.
  5. Truncate the URL if necessary to keep it within a reasonable length (ideally, less than 60 characters).


Here's an example implementation in Python:

1
2
3
4
5
def create_seo_friendly_url(string):
    string = string.lower().replace(' ', '-').replace('/', '-')
    string = re.sub(r'[^a-z0-9-]', '', string)
    string = re.sub(r'-+', '-', string).strip('-')
    return string[:60]


by kyleigh.wolff , a year ago

@aniyah 

This function takes a string as an input and performs the necessary steps to create a SEO-friendly dash-delimited URL. Here are the steps explained in more detail:

  1. Convert the string to lowercase using the lower() function to ensure consistency.
  2. Replace spaces and other non-alphanumeric characters with a dash "-" using the replace() function. This step helps in creating a clean URL without special characters.
  3. Remove any additional consecutive dashes that may have been created as a result of step 2 using the re.sub() function. The regular expression '-+' matches one or more consecutive dashes and replaces them with a single dash.
  4. Remove any trailing dashes from the URL using the strip() function.
  5. Finally, truncate the URL if necessary to keep it within a reasonable length (e.g., 60 characters) using slicing.


Note: In the implementation provided, the function uses the re module from Python's built-in regular expression library to remove non-alphanumeric characters and consecutive dashes. Therefore, you need to import the re module at the start of your Python script or function.

Member

by dortha , a year ago

@aniyah 

Here's an updated implementation that uses the re module:

1
2
3
4
5
6
7
import re

def create_seo_friendly_url(string):
    string = string.lower().replace(' ', '-').replace('/', '-')
    string = re.sub(r'[^a-z0-9-]', '', string)
    string = re.sub(r'-+', '-', string).strip('-')
    return string[:60]


With this function, you can now call create_seo_friendly_url(string) and pass in your desired string to get the SEO-friendly dash-delimited URL.