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?
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.
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).
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.
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.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With