PTIT-D22KH / milktea_sales_management_project

Java OOP Project - 24-25 Term 1
1 stars 0 forks source link

Giải thích Class StringToSlug #16

Closed duongvu5 closed 1 month ago

duongvu5 commented 1 month ago

StringToSlug Function

The StringToSlug function in the StringToSlug class is designed to convert a given string into a URL-friendly "slug". A slug is typically used in URLs to make them more readable and SEO-friendly. Here's a step-by-step explanation of how the convert method works:

Code Excerpt

public class StringToSlug {
    private static final Pattern NONLATIN = Pattern.compile("[^\\w-]");
    private static final Pattern WHITESPACE = Pattern.compile("[\\s_\\(]");

    public static String convert(String input) {
        String nowhitespace = WHITESPACE.matcher(input).replaceAll("-");
        String normalized = Normalizer.normalize(nowhitespace, Form.NFD);
        String slug = NONLATIN.matcher(normalized).replaceAll("");
        return slug.toLowerCase(Locale.ENGLISH);
    }
}

Step-by-Step Explanation

  1. Pattern Compilation:

    • NONLATIN: This pattern matches any character that is not a word character \w or a hyphen -. Essentially, it matches any non-Latin character.
    • WHITESPACE: This pattern matches any whitespace character \s, underscore _, or opening parenthesis (.
  2. Method convert:

    • Input: The method takes a single String parameter named input.
  3. Replace Whitespace and Underscores:

    String nowhitespace = WHITESPACE.matcher(input).replaceAll("-");
    • This line replaces all whitespace characters, underscores, and opening parentheses in the input string with hyphens -. The result is stored in the nowhitespace variable.
  4. Normalize the String:

    String normalized = Normalizer.normalize(nowhitespace, Form.NFD);
    • This line normalizes the string to the Unicode Normalization Form D (NFD). This form separates combined characters into their base characters and combining diacritical marks. For example, "é" becomes "e" followed by an accent character.
  5. Remove Non-Latin Characters:

    String slug = NONLATIN.matcher(normalized).replaceAll("");
    • This line removes all non-Latin characters from the normalized string. The result is stored in the slug variable.
  6. Convert to Lowercase:

    return slug.toLowerCase(Locale.ENGLISH);
    • Finally, the method converts the resulting slug to lowercase using the English locale and returns it.

Example

Let's see an example of how the convert method works:

Summary

The convert method in the StringToSlug class transforms a given string into a URL-friendly slug by replacing whitespace and certain characters with hyphens, normalizing the string, removing non-Latin characters, and converting the result to lowercase.