If I have a string loaded into a variable, what's the appropriate method to use to determine if the string ends in "/" forward slash?
var myString = jQuery("#myAnchorElement").attr("href");
If I have a string loaded into a variable, what's the appropriate method to use to determine if the string ends in "/" forward slash?
var myString = jQuery("#myAnchorElement").attr("href");
A regex works, but if you want to avoid that whole cryptic syntax, here's something that should work: 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
...
}
You don't need JQuery for that.
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
You can also write a prototype
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