encode_url.js 469 B

123456789101112131415161718192021
  1. 'use strict';
  2. const { parse, format } = require('url');
  3. const { unescape } = require('querystring');
  4. const encodeURL = str => {
  5. if (parse(str).protocol) {
  6. const parsed = new URL(str);
  7. // Exit if input is a data url
  8. if (parsed.origin === 'null') return str;
  9. parsed.search = encodeURI(unescape(parsed.search));
  10. // preserve IDN
  11. return format(parsed, { unicode: true });
  12. }
  13. return encodeURI(unescape(str));
  14. };
  15. module.exports = encodeURL;