Appending a trailing slash if needed

Posted on

Problem

I like to overcomplicate things, this is fairly simple though but I would like to keep it simpler without lowering readability. Not just to improve my code but also my self.

private String checkTrailingSlash(String website) {
    if(!website.endsWith("/")){
        website = website + "/";
    }
    return website;
}

Solution

You could use a ternary operator to inline the condition into a single return statement:

private String checkTrailingSlash(String website) {
    return website.endsWith("/") ? website : website + "/";
}

Honestly, I’m not sure how much simpler you can make this.

I’d suggest a slightly clearer name though – maybe ensureTrailingSlash? checkX sounds more like a predicate. My other suggestion would be to add some spaces in your if-conditional, depending on your taste:

if (!website.endsWith("/")) {

This could be a static method, as well.

It would be less verbose to write

website += "/";

instead of

website = website + "/";

So, yeah, you totally overcomplicated it. =)

Also, instead of checkTrailingSlash, it would be clearer if renamed to ensureTrailingSlashExists.

If you don’t like if statements in your code, then you could use something like this:

website=website.replaceAll("([^/])$","$1/") ;

it uses a regex to replace last character only if it is NOT a / with the last character plus the /.

Since often browsers also support backslashes, you can also consider this:

public static String addTrailingSlashIfMissing(String str) {
    String slashChar = str.contains("\") ? "\" : "/";
    return str.endsWith(slashChar) ? str : str + slashChar;
}

which can be also useful for file system paths.

Leave a Reply

Your email address will not be published. Required fields are marked *