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

Viewed 58343

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?

9 Answers

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.

The URL class is pretty awesome - it helps us change the path and takes care of query parameters and fragment identifiers

function addTrailingSlash(u) {
    const url = new URL(u);
    url.pathname += url.pathname.endsWith("/") ? "" : "/";
    return url.toString();
}

addTrailingSlash('http://example.com/slug?page=2');
// result: "http://example.com/slug/?page=2"

You can read more about URL on MDN

For those who use different inputs: like http://example.com or http://example.com/eee. It should not add a trailling slash in the second case.

There is the serialization option using .href which will add trailing slash only after the domain (host).

In NodeJs,

You would use the url module like this: 
const url = require ('url');
let jojo = url.parse('http://google.com')
console.log(jojo);

In pure JS, you would use

var url = document.getElementsByTagName('a')[0];
var myURL = "http://stackoverflow.com";
console.log(myURL.href);
Related