Skip to content

Add method to convert a URI string to a uri object? #29

@pdehaan

Description

@pdehaan

I've always been a bit confused by this uri object thing:

var uri = {
  spec: "http://fakehost/test/page.html",
  host: "fakehost",
  prePath: "http://fakehost",
  scheme: "http",
  pathBase: "http://fakehost/test"
};
var result = new window.Readability(uri, window.document).parse();

It seems that all the fields can be extracted from the spec string. It'd be nice if there were just some helper function which converts a fully qualified URL into a host, prePath, scheme, and pathBase for you.

Or maybe modify the window.Readability() method to accept an object or string, and if it's a URI string, try and auto-convert it to an object.

I'm guessing this would be pretty trivial w/ Node.js' url.parse() function, but it may fit better in the Readability.js library as plain olde JavaScript.

var url = require('url');

function uriFromString(str) {
  var urlObj = url.parse(str, true);
  var protocol = urlObj.protocol.replace(':', '');
  var prePath = protocol + '://' + urlObj.hostname;
  var uri = {
    spec: urlObj.href,
    host: urlObj.hostname,
    pathBase: prePath + urlObj.pathname.replace(/[^\/]+$/, ''),
    prePath: prePath,
    scheme: protocol
  };
  return uri;
}

console.log(JSON.stringify(uriFromString(uri.spec), null, 2));

I think we've also used http://medialize.github.io/URI.js/ in other projects (via Bower).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions