I want to remove the trailing slash from a string in Java.
I want to check if the string ends with a url, and if it does, i want to remove it.
Here is what I have:
String s = "http://almaden.ibm.com/"; s= s.replaceAll("/","");
and this:
String s = "http://almaden.ibm.com/"; length = s.length(); --length; Char buff = s.charAt((length); if(buff == '/') { LOGGER.info("ends with trailing slash"); /*how to remove?*/ } else LOGGER.info("Doesnt end with trailing slash");
But neither work.
Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.
Trailing slashes after the domain name don't matter These URLs are treated exactly the same and it doesn't matter which version you use.
What is a trailing slash? A trailing slash is a forward slash placed at the end of a URL. It's usually used to indicate a directory (as opposed to a file), but in SEO it can affect your rankings. Take a look at the URLs below and guess which one is 'correct'.
String s = "http://almaden.ibm.com/"; s= s. replaceAll("/",""); and this: String s = "http://almaden.ibm.com/"; length = s.
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("/*$", "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With