Shipow
Shipow

Reputation: 2447

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 !

Upvotes: 4

Views: 6394

Answers (4)

Sai Kiran
Sai Kiran

Reputation: 301

I created this filter

angular.module('App').filter( 'domainOfUrl',['$filter',function ($filter) {
  return function ( input ) {
     var urlParts = input.split('/');      
    return urlParts[2];
  };
}]);

The above filter works like this:

input : https://www.amazon.in/b/ref=s9_acss_bw_***_x

output: www.amazon.in

use $filter if you want.

Upvotes: 0

Benjamin Conant
Benjamin Conant

Reputation: 1734

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}}

Upvotes: 7

Josh David Miller
Josh David Miller

Reputation: 120513

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!

Upvotes: 13

leepowers
leepowers

Reputation: 38318

Use location.hostname to get the domain without an accruements.

http://fiddle.jshell.net/TUeJ7/

Upvotes: 0

Related Questions