Return string without trailing slash
I'd use a regular expression:
function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}
You'll want to make sure that the variable site
is a string, though.
function stripTrailingSlash(str) {
if(str.substr(-1) === '/') {
return str.substr(0, str.length - 1);
}
return str;
}
Note: IE8 and older do not support negative substr offsets. Use str.length - 1
instead if you need to support those ancient browsers.
Try this:
function someFunction(site)
{
return site.replace(/\/$/, "");
}
ES6 / ES2015 provides an API for asking whether a string ends with something, which enables writing a cleaner and more readable function.
const stripTrailingSlash = (str) => {
return str.endsWith('/') ?
str.slice(0, -1) :
str;
};