lisovaccaro
lisovaccaro

Reputation: 33946

Remove '/' at the end of string?

I'm using this function to remove http://, https:// and www. from my URLs.

function cleanUrl2(url) { 
    return url.replace(/^(http(s)?:\/\/)?(www\.)?/gi,"");
}

My problem is that I sometimes get:

google.com

and sometimes:

google.com/something/

The '/' at the end causes a lot of problems with my database. I need my function to also remove '/' if it's the last character.

How can I do this?

Upvotes: 0

Views: 163

Answers (5)

KARASZI István
KARASZI István

Reputation: 31467

The URL google.com/something/ is not equivalent with google.com/something the webserver (or code behind it) decides which data is being served when requesting these URLs.

And also www.google.com is not the same as google.com, maybe they even point to different IP addresses on different machines.

So before you make any replacements think about this.

Upvotes: 3

Michael Low
Michael Low

Reputation: 24506

url = url.replace(/\/$/, "");

But are you sure you want to be doing this ? Depending on the web server, the URL won't necessarily work if you remove the trailing slash. You'd be better off fixing the problem with your database code that's causing having a trailing slash to be an issue really.

Upvotes: 1

robermorales
robermorales

Reputation: 3488

Try

"google.com/something/".replace(/\/$/,"")

Upvotes: 1

Eineki
Eineki

Reputation: 14909

function cleanUrl2() {
    return url.replace(/^(http(s)?:\/\/)?(www\.)?|\/$/gi,"");
}

should do the trick (on ff does)

Upvotes: 1

Petar Ivanov
Petar Ivanov

Reputation: 93010

function cleanUrl2(url) { 
    return url.replace(/^(http(s)?:\/\/)?(www\.)?/gi,"").replace(/\/$/, "");
 }

Upvotes: 1

Related Questions