javascript/jquery add trailing slash to url (if not present)

var lastChar = url.substr(-1); // Selects the last character
if (lastChar != "https://stackoverflow.com/") {         // If the last character is not a slash
   url = url + "https://stackoverflow.com/";            // Append a slash to it.
}

The temporary variable name can be omitted, and directly embedded in the assertion:

if (url.substr(-1) != "https://stackoverflow.com/") url += "https://stackoverflow.com/";

Since the goal is changing the url with a one-liner, the following solution can also be used:

url = url.replace(/\/?$/, "https://stackoverflow.com/");
  • If the trailing slash exists, it is replaced with /.
  • If the trailing slash does not exist, a / is appended to the end (to be exact: The trailing anchor is replaced with /).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)