2013-02-08 5 views
9

文字列が変数にロードされている場合、文字列が "/"スラッシュで終わるかどうかを判断するのに適切な方法は何ですか?文字列がスラッシュで終了するかどうかを調べるためのJavaScript

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

を書くことができます。しかし、JavaScriptはできます。 –

+0

[文字列の最後の文字を取得する方法は?](http://stackoverflow.com/questions/3884632/how-to-get-the-last-character-of-a-string) –

答えて

12

正規表現作品を、しかし、あなたはその全体の不可解な構文を避けたい場合は、ここで働いべきものです:「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 
    ... 
} 
3

使用regexと実行します。

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

EDIT:あなたがチェックする必要があるだろう、心に留めておいてください

myString.match(/\/$/) 
1

簡単な解決策は、単に経由で最後の文字をチェックすることです最初に例外をスローしないようにするために、文字列がnullでないことを確認してください。

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 

また、jQueryのはそれを行うことはできませんプロトタイプ

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 
関連する問題