Class OpenSlug

java.lang.Object
cloud.opencode.base.string.OpenSlug

public final class OpenSlug extends Object
URL Slug Generator - Converts strings to URL-friendly slugs. URL别名生成器 - 将字符串转换为URL友好的别名。

A slug is a URL-friendly string derived from a human-readable text. This utility strips accents, lowercases, replaces non-alphanumeric characters with a separator, and collapses consecutive separators.

别名是从人类可读文本派生的URL友好字符串。本工具会去除变音符号、转为小写、 将非字母数字字符替换为分隔符,并折叠连续的分隔符。

Features | 主要功能:

  • Accent stripping via NFD normalization - 通过NFD标准化去除变音符号
  • Configurable separator - 可配置的分隔符
  • Max length with word-boundary awareness - 最大长度且不在分隔符中间截断

Usage Examples | 使用示例:

OpenSlug.toSlug("Hello World!")          // "hello-world"
OpenSlug.toSlug("Crème Brûlée")        // "creme-brulee"
OpenSlug.toSlug("foo bar", "_")          // "foo_bar"
OpenSlug.toSlug("a very long title", "-", 10)  // "a-very"

Performance | 性能特性:

  • Time complexity: O(n) - 时间复杂度: O(n)
  • Space complexity: O(n) - 空间复杂度: O(n)

Security | 安全性:

  • Thread-safe: Yes (stateless utility) - 线程安全: 是(无状态工具类)
  • Null-safe: Yes - 空值安全: 是
Since:
JDK 25, opencode-base-string V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • toSlug

      public static String toSlug(String str)
      Convert a string to a URL-friendly slug using "-" as separator. 将字符串转换为URL友好的别名,使用"-"作为分隔符。

      Algorithm | 算法:

      1. Strip accents (NFD normalization) - 去除变音符号
      2. Convert to lowercase - 转为小写
      3. Replace non-alphanumeric with separator - 替换非字母数字字符
      4. Collapse consecutive separators - 折叠连续分隔符
      5. Trim leading/trailing separators - 去除首尾分隔符
      Parameters:
      str - the input string | 输入字符串
      Returns:
      the slug | 别名
    • toSlug

      public static String toSlug(String str, String separator)
      Convert a string to a URL-friendly slug using a custom separator. 将字符串转换为URL友好的别名,使用自定义分隔符。
      Parameters:
      str - the input string | 输入字符串
      separator - the separator to use | 要使用的分隔符
      Returns:
      the slug | 别名
    • toSlug

      public static String toSlug(String str, String separator, int maxLength)
      Convert a string to a URL-friendly slug with a maximum length. 将字符串转换为URL友好的别名,带最大长度限制。

      The slug is truncated at a separator boundary so that no partial words remain. If no separator is found within the limit, the slug is truncated at maxLength.

      别名会在分隔符边界处截断,不留部分单词。如果在限制范围内找不到分隔符, 则在maxLength处截断。

      Parameters:
      str - the input string | 输入字符串
      separator - the separator to use | 要使用的分隔符
      maxLength - the maximum length of the slug | 别名的最大长度
      Returns:
      the slug | 别名
      Throws:
      IllegalArgumentException - if maxLength is negative | 如果maxLength为负数