javascript JQuery检查并从URL读取的末尾删除斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4740364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery check and remove slash from the end of URL read
提问by rem
In a jQuery script I have the line of code which gets the string of current URL:
在 jQuery 脚本中,我有一行代码可以获取当前 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?
此脚本中的代码能否检查 URL 字符串末尾是否有斜线。如果存在,则将其删除?有什么方法可以做,你可以推荐吗?
回答by Pointy
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.
然后事情变得有点棘手。使用正则表达式解析 URL 可能是可能的,但它非常混乱。如果您能侥幸逃脱,请缩小您的 URL 外观的可能性,这样您就不必使用一些巨大的“官方”模式。
回答by Mike Ruhlin
This should be safe for URLs with query strings as well, AND it doesn't use a regex....
这对于带有查询字符串的 URL 也应该是安全的,并且它不使用正则表达式......
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));
}
}
回答by Felix Kling
Assuming you mean a slash, one possible solution would be:
假设您的意思是斜线,一种可能的解决方案是:
var l = target.length - 1;
if(target.lastIndexOf('/') === l) {
target = target.substring(0, l);
}
回答by JJ Blumenfeld
You can do it with a regex like:
你可以用一个正则表达式来做到这一点:
target.replace(//+((\?|#).*)?$/, '$1');
target.replace(//+((\?|#).*)?$/, '$1');
Which should preserve query strings or url fragments at the end of the URL.
哪个应该在 URL 的末尾保留查询字符串或 url 片段。

