Vue URL Filters

Apr 13 2017

Using this simple technique to parse a URL using the DOM and an anchor, we can create some useful Vue template filters.

For example, to display the host of a url in your template:

import Vue from 'vue';

export default Vue.filter('host', function (url) {
  const parser = document.createElement('a');
  parser.href = url;
  return parser.host;
});

Then invoked like so:

{{ url | host }}

This could easily be extended to protocol, hostname, port, pathname, search, and hash.