Takes a normal string and turns it into something suitable for a title in a URL. - Java Network

Java examples for Network:URL

Description

Takes a normal string and turns it into something suitable for a title in a URL.

Demo Code


//package com.java2s;

public class Main {
    /**/*from  ww  w  .ja v  a2s.c o m*/
     * Takes a normal string and turns it into something suitable for a title in a URL.
     * This is all about SEO.  Basically, spaces go to dash and anything that isn't
     * URL-friendly gets stripped out.
     */
    public static String makeTitle(String title) {
        if (title == null)
            return "";

        StringBuilder bld = new StringBuilder();

        for (int i = 0; i < title.length(); i++) {
            char ch = title.charAt(i);

            if (Character.isWhitespace(ch))
                bld.append('-');
            else if (Character.isLetterOrDigit(ch))
                bld.append(ch);

            // otherwise skip
        }

        // Strip out any extra -'s that might get generated
        String dedup = bld.toString().replaceAll("-+", "-");
        if (dedup.charAt(dedup.length() - 1) == '-') {
            return dedup.substring(0, dedup.length() - 1);
        }
        return dedup;
    }
}

Related Tutorials