Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten url to show domain only with angular.js filter

I got some long urls in my Json and I'm trying to figure out the best way to show only the domain using angular's filter or maybe just some javascript ?

http://www.example.com/page-with-a-long-long-long-OMG-so-long-name.html

to

www.example.com

thank you !

like image 903
Shipow Avatar asked Dec 01 '22 04:12

Shipow


2 Answers

It's really easy in AngularJS to create your own filter:

app.filter( 'domain', function () {
  return function ( input ) {
    var matches,
        output = "",
        urls = /\w+:\/\/([\w|\.]+)/;

    matches = urls.exec( input );

    if ( matches !== null ) output = matches[1];

    return output;
  };
});

Which you can easily call in your view:

<span>{{ myUrl | domain }}</span>

Here's a Plunker: http://plnkr.co/edit/bVSv7n?builder&p=preview

This is a super-simple regex that you'll probably want to expand, but it works!

like image 127
Josh David Miller Avatar answered Dec 02 '22 16:12

Josh David Miller


This angular filter will also work!

It is really cool and simple because it makes use of of the browsers built in URI parsing capability instead of relying on a regex.

angular.module('myCoolApp')
  .filter('urlFilter', function ($document) {
    return function (input) {
      var parser = document.createElement('a');
      parser.href = input;
      return parser.hostname;
  };
});

You can implement it in your view like this.

{{ myLongURL | urlFilter }}

If myLongURL is http://www.example.com/page-with-a-long-long-long-OMG-so-long-name.html, then it will show up as example.com after it passes through the filter. If you want the www. at the beginning you can just do this!

www.{{myLongURL | urlFilter}}
like image 33
Benjamin Conant Avatar answered Dec 02 '22 17:12

Benjamin Conant