开发者

JQuery check and remove slash from the end of URL read

开发者 https://www.devze.com 2023-02-05 19:56 出处:网络
In a jQuery script I have the line of code which gets the string of current URL: var target = $(this).attr(\'href\');

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 prese开发者_运维问答nt then remove it? What is the way to do it, you could recommend?


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));
    }    
}


Assuming you mean a slash, one possible solution would be:

var l = target.length - 1;
if(target.lastIndexOf('/') === l) {
    target = target.substring(0, l);
}


You can do it with a regex like:

target.replace(//+((\?|#).*)?$/, '$1');

Which should preserve query strings or url fragments at the end of the URL.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号