Remove a trailing slash from a string(changed from url type) in JAVA
There are two options: using pattern matching (slightly slower):
s = s.replaceAll("/$", "");
or:
s = s.replaceAll("/\\z", "");
And using an if statement (slightly faster):
if (s.endsWith("/")) {
s = s.substring(0, s.length() - 1);
}
or (a bit ugly):
s = s.substring(0, s.length() - (s.endsWith("/") ? 1 : 0));
Please note you need to use s = s...
, because Strings are immutable.
This should work better:
url.replaceFirst("/*$", "")
simple method in java
String removeLastSlash(String url) {
if(url.endsWith("/")) {
return url.substring(0, url.lastIndexOf("/"));
} else {
return url;
}
}