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");
The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.
First, find the last index of ('/') using . lastIndexOf(str) method. Use the . substring() method to get the access the string after last slash.
We should double for a backslash escape a forward slash / in a regular expression. A backslash \ is used to denote character classes, e.g. \d . So it's a special character in regular expression (just like in regular strings).
The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate. This method is case-sensitive.
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
...
}
Use regex
and do:
myString.match(/\/$/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With