java – Remove URL Prefix from String (http:/, www, etc.)-ThrowExceptions

Exception or error:

I need to remove all kinds of “web beginnings” from my String

My TextView must be without “http://” , “http:// www.” , “www.” and other URL prefixes.

Please can you help me to to this ?

How to solve:

You can do that by using regular expression



Use an instance of URI and use it to split however you want:

URI uri = new URI(whateverYourAddressStringIs);
String path = uri.getPath(); // split whatever you need


you can use String replace.

String myString = "";
myString.replace("http://","").replace("http:// www.","").replace("www.","");


I assume that when you say “web beginnings”, you mean “protocols”. You can learn more about URLs in the RFC, or wikipedia.

Generally speaking, you cannot remove “www.” from a URL and guarantee that the URL will point to the same host. If all you want to do is hide it from the user, that’s fine, but I personally find that annoying.

The following code will strip all protocols that Java knows about, not just http. Not all protocols have a //, so you have to manually check that. The Java URL class can break down the URL as precisely as you want it.


public class test
    public static void main(String[] args)
        try {
            URL url = new URL(args[0]);
            String protocol = url.getProtocol();
            String result = args[0].replaceFirst(protocol + ":", "");
            if (result.startsWith("//"))
                result = result.substring(2);

        } catch (Exception e) {


You can use String.replace() method.

Leave a Reply

Your email address will not be published. Required fields are marked *