如何创建一个URL slug扩展名



我正在使用Spring和Kotlin创建一个博客应用程序。对于每篇文章,我都需要编程生成一个sl。例如,如果文章标题是"奇瓦瓦人如何越过道路",则slug应该是" chihuahua-crossed-the-the-the-the-road"。

对于上下文,我的实体文件(截断(看起来像:

@Entity
class Article(
    var title: String,
    var slug: String = I_WANT_THIS_TO_BE_A_SLUG_FROM_THE_TITLE)

如何使用Kotlin扩展名来实现此操作?

在您的Extensions.kt文件中,添加以下代码:

fun String.toSlug() = toLowerCase()
        .replace("n", " ")
        .replace("[^a-z\d\s]".toRegex(), " ")
        .split(" ")
        .joinToString("-")
        .replace("-+".toRegex(), "-")

然后使用实体文件中的扩展名:

@Entity
class Article(
    var title: String,
    var slug: String = title.toSlug())

此外,如果您不希望sl lug可变,请将其添加为计算的属性:

@Entity
class Article(
        var title: String) {
    val slug get() = title.toSlug()
}

参考

我从Spring Boot和Kotlin(由SébastienDeleuze撰写(中学到了Slug扩展程序。有关完整上下文,请参见扩展。

另外,感谢戴夫·利兹(Dave Leeds(推荐了计算的属性选项。在Kotlin上查看他的Kotlin博客Dave Leeds,以了解深入的概念和指南。

其他解释的另一种方式

import java.text.Normalizer
fun String.slugify(): String = Normalizer
                .normalize(this, Normalizer.Form.NFD)
                .replace("[^\w\s-]".toRegex(), "") // Remove all non-word, non-space or non-dash characters
                .replace('-', ' ') // Replace dashes with spaces
                .trim() // Trim leading/trailing whitespace (including what used to be leading/trailing dashes)
                .replace("\s+".toRegex(), "-") // Replace whitespace (including newlines and repetitions) with single dashes
                .toLowerCase() // Lowercase the final results

我创建了一个GIST https://gist.github.com/raychenon/8fac7e5fb41364694f00ee6ce8b8c32a8

最新更新