原生js.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // npm install urijs
  2. var URI = require('urijs');
  3. var uri = new URI("/relative/path");
  4. // let c = URI.resolve('http://example.com/one', '/two');
  5. // let d = URI.resolve('http://example.com/one', 'http://www.baidu.com');
  6. // console.log(c);
  7. // console.log(d);
  8. var uri2 = URI("../foobar.html", "http://example.org/hello/world.html");
  9. console.log(uri2.toString())
  10. uri2 = URI('http://www.baidu.com', 'http://example.com/one');
  11. console.log(uri2.toString())
  12. uri2 = URI('', 'http://example.com/one');
  13. console.log(uri2.toString())
  14. function urljoin(fromPath, nowPath) {
  15. let new_uri = URI(nowPath, fromPath);
  16. new_uri = new_uri.toString();
  17. // console.log(new_uri);
  18. // return fromPath + nowPath
  19. return new_uri
  20. }
  21. console.log(urljoin('http://example.com/one','/detail/1.html'));
  22. console.log(urljoin('http://example.com/one/path/','detail/1.html'));
  23. console.log(urljoin('http://example.com/one','http://www.baidu.com'));
  24. console.log(urljoin('https://example.com/one','//path/1.png'));
  25. // make path relative
  26. var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
  27. // relUri == "../../../path"
  28. // absolute URLs are passed through unchanged
  29. let a = URI("http://example.org/world.html").relativeTo("http://google.com/baz");
  30. console.log(a.toString())
  31. // -> "http://example.org/world.html"
  32. // absolute URLs relative to absolute URLs
  33. // may resolve the protocol
  34. URI("http://example.org/world.html")
  35. .clone()
  36. .authority("")
  37. .relativeTo("http://google.com/baz");
  38. // -> "//google.com/world.html"
  39. // equal URLs are relative by empty string
  40. URI("http://www.example.com:8080/dir/file")
  41. .relativeTo('http://www.example.com:8080/dir/file');
  42. // -> ""
  43. // relative on fragment and query string as well
  44. URI("http://www.example.com:8080/dir/file?foo=bar#abcd")
  45. .relativeTo('http://www.example.com:8080/dir/file');