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 !
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!
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With