Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a trailing slash from a string(changed from url type) in JAVA

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.

like image 572
Eswar Rajesh Pinapala Avatar asked Mar 25 '11 19:03

Eswar Rajesh Pinapala


People also ask

How do you remove the last slash from a string?

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.

Does a trailing slash in URL matter?

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 in URL?

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'.

How do I remove the last slash from a URL in Java?

String s = "http://almaden.ibm.com/"; s= s. replaceAll("/",""); and this: String s = "http://almaden.ibm.com/"; length = s.


2 Answers

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.

like image 68
Thomas Mueller Avatar answered Oct 11 '22 19:10

Thomas Mueller


This should work better:

url.replaceFirst("/*$", "") 
like image 21
Anton Avatar answered Oct 11 '22 19:10

Anton