Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 921
jackweirdy Avatar asked Jul 17 '12 21:07

jackweirdy


People also ask

How do you add a trailing slash to a URL?

A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash.

Should I add trailing slash to URL?

Historically, a trailing slash marked a directory and a URL without a trailing slash at the end used to mean that the URL was a file. Today, however, trailing slashes are purely conventional, and Google does not care whether you use them; as long as you're consistent.

Is trailing slash required?

The trailing slash does not matter for your root domain or subdomain. Google sees the two as equivalent. But trailing slashes do matter for everything else because Google sees the two versions (one with a trailing slash and one without) as being different URLs.

How do you fix trailing slash issues?

A 301 redirect is the best way to resolve duplicate content issues caused by trailing slashes. If you're just fixing one page, you'd redirect the duplicate copy to the version that matches your chosen URL structure. Most trailing slash issues however, affect many pages across a website.


1 Answers

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 /).
like image 79
5 revs, 3 users 36% Avatar answered Sep 23 '22 20:09

5 revs, 3 users 36%