2013-02-08 176 views
9

如果我有一个字符串加载到变量中,用什么方法判断字符串是否以“/”正斜杠结尾?JavaScript查找字符串是否以正斜杠结尾

var myString = jQuery("#myAnchorElement").attr("href"); 
+0

jQuery的不能做到这一点。但是,JavaScript可以。 – 2013-02-08 16:19:28

+0

[如何获得字符串的最后一个字符?]的可能重复(http://stackoverflow.com/questions/3884632/how-to-get-the-last-character-of-a-string) – 2013-02-08 16:20:46

回答

3

使用regex做:

myString.match(/\/$/) 
1

一个简单的解决办法是通过只检查最后一个字符:

var endsInForwardSlash = myString[myString.length - 1] === "/"; 

编辑:请记住,你需要检查该字符串不为空以防止抛出异常。

1

您可以使用子和lastIndexOf:

var value = url.substring(url.lastIndexOf('/') + 1); 
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 
相关问题