Slugger - A Java library for creating nice URL Slugs
Instances of a
Slugger object provide a way to generate "slugs", that can
be used in URLs on the web. Inputs can be split into words in a variety of ways
and the length of the output can be restricted if required. Any
can be used as the joining character between consecutive words. Characters that
would require escaping in a URL are removed or replaced, as appropriate.
The simplest usage of
Slugger would be something like the following:
Slugger slugger = Slugger.create(); String firstTitle = slugger.sluggify("My first blog post"); // my-first-blog-post String secondTitle = slugger.sluggify("Another post!"); // another-post
This creates an instance of a
Slugger with the default configuration, which
splits the input on whitespace, removes special characters, and converts the
output to lowercase.
By default, a Slugger will split the supplied input into words based on whitespace, although a number of alternative word splitters are provided (and the interface is publicly exposed for extensibility).
To replace the default splitter, use the
method as follows:
Slugger slugger = Slugger.create().withWordSplitter(WordSplitters.camelCaseWordSplitter()); slugger.sluggify("MyFirstBlogPost"); // my-first-blog-post
Splitters can also be chained, so you can split on both whitespace and camel-case, as follows:
Slugger slugger = Slugger.create().withAdditionalWordSplitter(WordSplitters.camelCaseWordSplitter()); slugger.sluggify("The importance of toString()"); //the-importance-of-to-string