JavaScriptでのURL末尾スラッシュ除去

stackoverflow.com

正規表現

正規表現で置換するパターン。

function removeTrailingSlash(url) {
  return url.replace(/\/$/, '')
}

String.prototype.substr()

substrで判定するパターン。

function removeTrailingSlash(url) {
  if (url.substr(-1) === '/') {
     url.substr(0, url.length - 1)
  }
  return url
}

developer.mozilla.org

String.prototype.endsWith()

判定はendsWithでやるパターン。es2015+で利用できる。

function removeTrailingSlash(url) {
  return url.endsWith('/') ? url.substr(0, url.length - 1) : url
}

developer.mozilla.org