How to format a website URL in Java

H

Most people want uniformity in their database. That is not always easy when you let the user enter data. Website URLs can come in all sizes. But how should you create an exactly uniform URL?

First, you have to check if the url is valid and not null, else you return null:

public static String formatWebsite(String website) {
    if (website != null && !website.trim().equals("")) {
        if (website.trim().toLowerCase().matches("((http|https)://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?")) {

        }
    }
    return null;
}

Then inside, the match case, you have to delete the protocols and www. (You can add protocols to filter by yourself.):

return "http://www." + website.trim().toLowerCase().replace("http://", "").replace("https://", "").replace("www.", "").replace("/", "").trim();

complete code:

public static String formatWebsite(String website) {
    if (!isNull(website)) {
        if (website.trim().toLowerCase().matches("((http|https)://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?")) {
            return "http://www." + website.trim().toLowerCase().replace("http://", "").replace("https://", "").replace("www.", "").replace("/", "").trim();
        }
    }
    return null;
}

Unit tests

assertEquals("http://www.laurenthinoul.com", FormatterCommons.formatWebsite("laurenthinoul.com"));
assertEquals("http://www.laurenthinoul.com", FormatterCommons.formatWebsite("http://laurenthinoul.com"));
assertEquals("http://www.laurenthinoul.com", FormatterCommons.formatWebsite("https://laurenthinoul.com"));
assertEquals("http://www.laurenthinoul.com", FormatterCommons.formatWebsite("www.laurenthinoul.com"));
assertEquals("http://www.laurenthinoul.com", FormatterCommons.formatWebsite("http://www.laurenthinoul.com"));
assertEquals("http://www.laurenthinoul.com", FormatterCommons.formatWebsite("https://www.laurenthinoul.com"));

assertEquals(null, FormatterCommons.formatWebsite("info@laurenthinoul.com"));
assertEquals(null, FormatterCommons.formatWebsite("http://laurenthinoul"));
assertEquals(null, FormatterCommons.formatWebsite("laurenthinoul"));
assertEquals(null, FormatterCommons.formatWebsite(""));
assertEquals(null, FormatterCommons.formatWebsite(null));

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud

Categories

%d bloggers like this: