最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to shorten url to show domain only with angular.js filter - Stack Overflow

programmeradmin6浏览0评论

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 ?

.html

to

www.example

thank you !

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./page-with-a-long-long-long-OMG-so-long-name.html

to

www.example.

thank you !

Share Improve this question asked Jan 30, 2013 at 0:56 ShipowShipow 2,4471 gold badge21 silver badges28 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 13

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./page-with-a-long-long-long-OMG-so-long-name.html, then it will show up as example. after it passes through the filter. If you want the www. at the beginning you can just do this!

www.{{myLongURL | urlFilter}}

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

http://fiddle.jshell/TUeJ7/

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.

发布评论

评论列表(0)

  1. 暂无评论