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

I'm making a small web app in which a user enters a server URL from which it pulls a load of data with an AJAX request.

Since the user has to enter the URL manually, people generally forget the trailing slash, even though it's required (as some data is appended to the url entered). I need a way to check if the slash is present, and if not, add it.

This seems like a problem that jQuery would have a one-liner for, does anyone know how to do this or should I write a JS function for it?


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

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

if (url.substr(-1) != '/') url += '/';

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

url = url.replace(/\/?$/, '/');
  • 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 /).

url += url.endsWith("/") ? "" : "/"

I added to the regex solution to accommodate query strings:

http://jsfiddle.net/hRheW/8/

url.replace(/\/?(\?|#|$)/, '/$1')

This works as well:

url = url.replace(/\/$|$/, '/');

Example:

let urlWithoutSlash = 'https://www.example.com/path';
urlWithoutSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithoutSlash);

let urlWithSlash = 'https://www.example.com/path/';
urlWithSlash = urlWithSlash.replace(/\/$|$/, '/');
console.log(urlWithSlash);

Output:

https://www.example.com/path/
https://www.example.com/path/

It replaces either the trailing slash or no trailing slash with a trailing slash. So if the slash is present, it replaces it with one (essentially leaving it there); if one is not present, it adds the trailing slash.