How to shorten the url to show the domain only using angular.js filter

I have a few long URLs in my Json and am trying to find a better way to show only the domain using the angular 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!

+4
source share
4 answers

In AngularJS, it is very easy 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; }; }); 

What you can easily call in your view:

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

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

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

+13
source

This angular filter will also work!

This is really cool and simple because it uses browsers created in URI parsing, rather than relying on a regular expression.

 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 as follows.

 {{ myLongURL | urlFilter }} 

If myLongURL http://www.example.com/page-with-a-long-long-long-OMG-so-long-name.html , then it will be displayed as example.com after passing through the filter. If you want www. in the beginning, you can just do it!

 www.{{myLongURL | urlFilter}} 
+7
source

Use location.hostname to get a domain without charges.

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

0
source

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 as follows:

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

output: www.amazon.in

use $filter if you want.

0
source

All Articles