Home > front end >  How to get a part of URL in string in Java
How to get a part of URL in string in Java

Time:07-20

Let assume there is a string such as "https://testdomain.com/12345/testdocument.pdf"

I need only "testdocument.pdf" part.

Important part is, there is no exact location. Character size can be changed but needed part will always be at the end of string

Anyone can help me?

CodePudding user response:

If you are sure that the needed part will be after the last '/' character, then what you can do is

String url = "https://testdomain.com/12345/testdocument.pdf";
String neededPart = url.substring(url.lastIndexOf("/")   1);

CodePudding user response:

considering that the url part you are interested in can be no longer the last one, you can try this:

    String url = "https://testdomain.com/12345/testdocument.pdf";
    final String PDF_EXTENSION = ".pdf";
    String neededPart = url.substring(url.lastIndexOf("/"), url.lastIndexOf(PDF_EXTENSION));
    System.out.println(neededPart   PDF_EXTENSION);

Output:

/testdocument.pdf

  • Related