如果我将一个字符串加载到变量中,用什么方法来确定字符串是否以“/”正斜杠结尾?
var myString = jQuery("#myAnchorElement").attr("href");
答案 0 :(得分:14)
正则表达式有效,但是如果你想避免那种完整的语法,那么这里应该有用:javascript/jquery add trailing slash to url (if not present)
var lastChar = url.substr(-1); // Selects the last character
if (lastChar !== '/') { // If the last character is not a slash
...
}
答案 1 :(得分:3)
使用regex
并执行:
myString.match(/\/$/)
答案 2 :(得分:1)
一个简单的解决方案是通过以下方式检查最后一个字符:
var endsInForwardSlash = myString[myString.length - 1] === "/";
编辑:请记住,您需要首先检查字符串是否为空,以防止抛出异常。
答案 3 :(得分:1)
您可以使用substring和lastIndexOf:
var value = url.substring(url.lastIndexOf('/') + 1);
答案 4 :(得分:0)
你不需要JQuery。
function endsWith(s,c){
if(typeof s === "undefined") return false;
if(typeof c === "undefined") return false;
if(c.length === 0) return true;
if(s.length === 0) return false;
return (s.slice(-1) === c);
}
endsWith('test','/'); //false
endsWith('test',''); // true
endsWith('test/','/'); //true
您也可以编写原型
String.prototype.endsWith = function(pattern) {
if(typeof pattern === "undefined") return false;
if(pattern.length === 0) return true;
if(this.length === 0) return false;
return (this.slice(-1) === pattern);
};
"test/".endsWith('/'); //true