[英]Javascript to find if string terminates in a forward slash
如果我將一個字符串加載到變量中,那么用什么方法來確定字符串是否以“/”正斜杠結尾?
var myString = jQuery("#myAnchorElement").attr("href");
一個正則表達式工作,但如果你想避免整個神秘的語法,這里的東西應該工作: javascript / jquery添加尾部斜杠到url(如果不存在)
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] === "/";
編輯:請記住,您需要首先檢查字符串是否為空,以防止拋出異常。
您可以使用substring和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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.