Extract part of a String using Java Substring

While working with java, we sometimes feel the need to extract some characters or part of a String to be able to use it for another logic.

Here is an example where we will need the value of a field called “id” to be extracted from a URL to be passed in another API request.

String urlText="https://google.com/authorize?redirect_uri=https://facebook.com&id=hdhfdfhdjfhdfhui9494&scope=test%test";

String id=mainString.substring(mainString.indexOf("&id")+4,
          mainString.indexOf("&scope"));
System.out.println(id);

Output:
hdhfdfhdjfhdfhui9494

Leave a Reply