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?
The temporary variable name can be omitted, and directly embedded in the assertion:
Since the goal is changing the url with a one-liner, the following solution can also be used:
/
./
is appended to the end (to be exact: The trailing anchor is replaced with/
).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,
In pure JS, you would use
Before finding this question and it's answers I created my own approach. I post it here as I don't see something similar.
This works as well:
Example:
Output:
Not every URL can be completed with slash at the end. There are at least several conditions that do not allow one:
index.html
./page?foo=1&bar=2
./page#tomato
.I have written a function for adding slash if none of the above cases are present. There are also two additional functions for checking the possibility of adding slash and for breaking URL into parts. Last one is not mine, I've given a link to the original one.
There might also be several cases when adding slash is not possible. If you know some, please comment my answer.
I added to the regex solution to accommodate query strings:
http://jsfiddle.net/hRheW/8/