Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery check and remove slash from the end of URL read

In a jQuery script I have the line of code which gets the string of current URL:

var target = $(this).attr('href');

Could the code in this script check if there is a slash at the end of the URL string. If it is present then remove it? What is the way to do it, you could recommend?

like image 579
rem Avatar asked Jan 19 '11 20:01

rem


People also ask

How do I remove the last slash from a URL?

Then preg_replace('{/$}', '', $_SERVER['REQUEST_URI']) will remove the slash and hand over to header() to redirect. The exit() function is important to stop any further code execution.

How do you find the last part of a URL?

We identify the index of the last / in the path, calling lastIndexOf('/') on the thePath string. Then we pass that to the substring() method we call on the same thePath string. This will return a new string that starts from the position of the last / , + 1 (otherwise we'd also get the / back).

What is a trailing slash?

A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash.


2 Answers

I'd do this:

 target = target.replace(/\/$/, '');

Now if you need to worry about the presence of a query string:

 <a href='http://foo.bar.com/something/?param=xyz'>hi</a>

then things get a little more tricky. Parsing a URL with a regex is probably possible, but it's pretty messy. If you can get away with it, narrow down the possibilities of what your URLs can look like so that you don't have to use some big huge "official" pattern.

like image 114
Pointy Avatar answered Oct 27 '22 01:10

Pointy


This should be safe for URLs with query strings as well, AND it doesn't use a regex....

var urlEnd = target.indexOf("?");
if(urlEnd == -1){
    urlEnd = target.length;
}

// Don't bother doing anything if the URL is empty
if (urlEnd > 0){
    if (target[urlEnd - 1] == "/"){
        $(this).attr('href', target.substr(0, urlEnd-1) + target.substr(urlEnd));
    }    
}
like image 34
Mike Ruhlin Avatar answered Oct 26 '22 23:10

Mike Ruhlin