51

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Eswar Rajesh Pinapala
  • 4,841
  • 4
  • 32
  • 40

11 Answers11

102

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.

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
  • Thanks for the response, Can i know if i could perform the same operation on a variable type URL, as i want to declare it as final. replaceAll doesnt seem to work on type URL Thanks for the replies again , i am a beginner in java ! – Eswar Rajesh Pinapala Mar 26 '11 at 00:06
  • 1
    `java.net.URL` can be converted to a `java.lang.String` using `toString()`. – Thomas Mueller Mar 26 '11 at 08:46
18

This should work better:

url.replaceFirst("/*$", "")
Anton
  • 181
  • 1
  • 2
13

You can achieve this with Apache Commons StringUtils as follows:

String s = "http://almaden.ibm.com/";
StringUtils.removeEnd(s, "/")
Babatunde Adeyemi
  • 14,360
  • 4
  • 34
  • 26
8

simple method in java

String removeLastSlash(String url) {
    if(url.endsWith("/")) {
        return url.substring(0, url.lastIndexOf("/"));
    } else {
        return url;
    }
}
Serhii Bohutskyi
  • 2,261
  • 2
  • 28
  • 28
7

url.replaceAll("/$", "") the $ matches the end of a string so it replaces the trailing slash if it exists.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
CarlosZ
  • 8,281
  • 1
  • 21
  • 16
  • Thanks for the response, Can i know if i could perform the same operation on a variable type URL, as i want to declare it as final. replaceAll doesnt seem to work on type URL Thanks for the replies again , i am a beginner in java ! – Eswar Rajesh Pinapala Mar 26 '11 at 00:06
2

Easiest way ...

String yourRequiredString = myString.subString(0,myString.lastIndexOf("/"));
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
2

a more compact way:

String pathExample = "/test/dir1/dir2/";

String trimmedSlash = pathExample.replaceAll("^/|/$","");

regexp ^/ replaces the first, /$ replaces the last

Community
  • 1
  • 1
2

As its name indicates, the replaceAll method replaces all the occurrences of the searched string with the replacement string. This is obviously not what you want. You could have found it yourself by reading the javadoc.

The second one is closer from the truth. By reading the javadoc of the String class, you'll find a useful method called substring, which extracts a substring from a string, given two indices.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

If you are a user of Apache Commons Lang you can take profit of the chomp method located in StringUtils

String s = "http://almaden.ibm.com/";

StringUtils.chomp(s,File.separatorChar+"")

Community
  • 1
  • 1
Dante
  • 324
  • 3
  • 7
  • Two-argument method is deprecated in favor of `removeEnd`: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#removeEnd-java.lang.String-java.lang.String- – berezovskyi May 02 '17 at 21:54
0

Kotlin side

    fun removeTrailSlash(s: String): String {
        return s.replace(Regex("/$"), "")
    }

    fun String.removeTrailSlash(): String {
        return CommonUtil.removeTrailSlash(this)
    }
    @Test
    fun removeTrailSlash() {
        // given
        val expected = "asdf/qwer"
        val s = "$expected/"
        // when
        val actual = CommonUtil.removeTrailSlash(s)
        // then
        assertEquals(expected, actual)
    }
    
    @Test
    fun removeTrailSlash() {
        // given
        val expected = "asdf/qwer"
        val s = "$expected/"
        // when
        val actual = s.removeTrailSlash()
        // then
        Assertions.assertEquals(expected, actual)
    }
seunggabi
  • 1,699
  • 12
  • 12
-1
   if (null != str && str.length > 0 )
    {
        int endIndex = str.lastIndexOf("/");
        if (endIndex != -1)  
        {
            String newstr = str.subString(0, endIndex); // not forgot to put check if(endIndex != -1)
        }
    }  
Sai Aditya
  • 2,353
  • 1
  • 14
  • 16