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("https://laurenthinoul.com", FormatterCommons.formatWebsite("laurenthinoul.com")); assertEquals("https://laurenthinoul.com", FormatterCommons.formatWebsite("https://laurenthinoul.com")); assertEquals("https://laurenthinoul.com", FormatterCommons.formatWebsite("https://laurenthinoul.com")); assertEquals("https://laurenthinoul.com", FormatterCommons.formatWebsite("www.laurenthinoul.com")); assertEquals("https://laurenthinoul.com", FormatterCommons.formatWebsite("https://laurenthinoul.com")); assertEquals("https://laurenthinoul.com", FormatterCommons.formatWebsite("https://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));