Remove a trailing slash from a string (i.e. string) in java

In many cases, we may need to remove the trailing slash from the end of the string. We can discuss the following use cases.

Let say we have an URL that sometimes may have a trailing slash at the end and sometimes may not. We want to add a query parameter at the end of the URL.

Example URL:

https://api.sandbox.somedomain.com/story/v2/story
or 
https://api.sandbox.somedomain.com/story/v2/story/
or 
https://api.sandbox.somedomain.com/story/v2/story////

In this case if we want to add something at the end of the URL is bit tricky. It is better to cleanup the trailing slash and add something with the slash.

In Java, we can very easily do that.

var articleApi = "https://api.sandbox.somedomain.com/story/v2/story///";
var articleApi = articleApi.replaceFirst("/*$", "");
System.out.println(articleApi);

// output
https://api.sandbox.somedomain.com/story/v2/story

`replaceFirst` uses a pattern and inside the patter we said match multiple of them and replace with empty string.