How To Shorten Url To Show Domain Only With Angular.js Filter
Solution 1:
It's really easy in AngularJS to create your own filter:
app.filter( 'domain', function () {
returnfunction ( 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!
Solution 2:
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) {
returnfunction (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}}
Solution 3:
Use location.hostname
to get the domain without an accruements.
Solution 4:
I created this filter
angular.module('App').filter( 'domainOfUrl',['$filter',function($filter) {
returnfunction( 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.
Post a Comment for "How To Shorten Url To Show Domain Only With Angular.js Filter"