url-join.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. (function (name, context, definition) {
  2. if (typeof module !== 'undefined' && module.exports) module.exports = definition();
  3. else if (typeof define === 'function' && define.amd) define(definition);
  4. else context[name] = definition();
  5. })('urljoin', this, function () {
  6. function normalize (strArray) {
  7. var resultArray = [];
  8. if (strArray.length === 0) { return ''; }
  9. if (typeof strArray[0] !== 'string') {
  10. throw new TypeError('Url must be a string. Received ' + strArray[0]);
  11. }
  12. // If the first part is a plain protocol, we combine it with the next part.
  13. if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) {
  14. var first = strArray.shift();
  15. strArray[0] = first + strArray[0];
  16. }
  17. // There must be two or three slashes in the file protocol, two slashes in anything else.
  18. if (strArray[0].match(/^file:\/\/\//)) {
  19. strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1:///');
  20. } else {
  21. strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, '$1://');
  22. }
  23. for (var i = 0; i < strArray.length; i++) {
  24. var component = strArray[i];
  25. if (typeof component !== 'string') {
  26. throw new TypeError('Url must be a string. Received ' + component);
  27. }
  28. if (component === '') { continue; }
  29. if (i > 0) {
  30. // Removing the starting slashes for each component but the first.
  31. component = component.replace(/^[\/]+/, '');
  32. }
  33. if (i < strArray.length - 1) {
  34. // Removing the ending slashes for each component but the last.
  35. component = component.replace(/[\/]+$/, '');
  36. } else {
  37. // For the last component we will combine multiple slashes to a single one.
  38. component = component.replace(/[\/]+$/, '/');
  39. }
  40. resultArray.push(component);
  41. }
  42. var str = resultArray.join('/');
  43. // Each input component is now separated by a single slash except the possible first plain protocol part.
  44. // remove trailing slash before parameters or hash
  45. str = str.replace(/\/(\?|&|#[^!])/g, '$1');
  46. // replace ? in parameters with &
  47. var parts = str.split('?');
  48. str = parts.shift() + (parts.length > 0 ? '?': '') + parts.join('&');
  49. return str;
  50. }
  51. return function () {
  52. var input;
  53. if (typeof arguments[0] === 'object') {
  54. input = arguments[0];
  55. } else {
  56. input = [].slice.call(arguments);
  57. }
  58. return normalize(input);
  59. };
  60. });