1

I have the following conditional statement in JS:

if(url === 'http://www.productionlocations.com/locations' || url === 'http://www.productionlocations.com/locations/')

I'm trying to make it more efficient so I tried this:

function stripTrailingSlash(str) {
    if(str.substr(-1) == '/') {
        return str.substr(0, str.length - 1);
    }
    return str;
}

theurl = stripTrailingSlash(url);                   
if(theurl === 'http://www.productionlocations.com/locations')

But obviously that just makes it into more code :)

What's the most efficient way of doing this? I had tried using indexOf() before, but it didn't work. Thanks for your help!

2
  • The conditional statement does not strip anything. If the stripping is not essentiell, do not do it! Commented May 11, 2012 at 14:58
  • A simpler way to remove a tailing slash: str.replace(/\\$/, '') Commented May 11, 2012 at 15:01

1 Answer 1

2

you can use test method:

if(/^http:\/\/www\.productionlocations\.com\/locations\/?$/.test(url)) {
    // code goes here
}
Sign up to request clarification or add additional context in comments.

4 Comments

It makes it hard to see the original test URL, and harder to maintain if the URL changes.
There is over 9000 solutions to check. I've provide mine ;)
if(/\/locations\/?$/.test(url)) Is totally doable. And accomplishes the same goal.
Yes, if you don't need to check domain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.