Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  151] [ 3]  / answers: 1 / hits: 62366  / 12 Years ago, tue, july 17, 2012, 12:00:00

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?


More From » jquery

 Answers
10
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 /).


[#84192] Tuesday, July 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julissaimana

Total Points: 593
Total Questions: 108
Total Answers: 112

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;