如果我有一个字符串加载到变量中,用什么方法判断字符串是否以“/”正斜杠结尾?JavaScript查找字符串是否以正斜杠结尾
var myString = jQuery("#myAnchorElement").attr("href");
如果我有一个字符串加载到变量中,用什么方法判断字符串是否以“/”正斜杠结尾?JavaScript查找字符串是否以正斜杠结尾
var myString = jQuery("#myAnchorElement").attr("href");
一个正则表达式的作品,但如果你想避免整个语法晦涩,这里的东西应该工作: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
...
}
使用regex
做:
myString.match(/\/$/)
一个简单的解决办法是通过只检查最后一个字符:
var endsInForwardSlash = myString[myString.length - 1] === "/";
编辑:请记住,你需要检查该字符串不为空以防止抛出异常。
您可以使用子和lastIndexOf:
var value = url.substring(url.lastIndexOf('/') + 1);
你不”为此需要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
jQuery的不能做到这一点。但是,JavaScript可以。 – 2013-02-08 16:19:28
[如何获得字符串的最后一个字符?]的可能重复(http://stackoverflow.com/questions/3884632/how-to-get-the-last-character-of-a-string) – 2013-02-08 16:20:46