当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to remove "http://" from domain name inside view

问题描述:

How can I remove "http://" from beginning of a URL inside view in an AngularJS app?

I have URLs in database like:

http://example.com/

http://example.com

example.com

but I only need to show

example.com

inside the view.

网友答案:

This deals with HTTP and HTTPS or any other URL. It uses the built-in URL class, which will handle all of the things you haven't thought of correctly.

  app.filter('domain', function () {
    return function (input) {
      try {
        var url = new URL(input);
        return url.hostname;
      } catch (DOMException) {
        // Malformed URL. Return original (or something else).
        return input; }
      };
    });

URLs that are correct and you might not have thought of:

  • http://example.com
  • http://example.com:8000
  • http://[email protected]
  • file://example.com
  • https://example.com
  • http://example.com/some-path
  • http://example.com?some-query-url

You may not need them now, but using the correct library function means your app won't break unexpectedly in future when someone tries to use it for something else.

网友答案:

use this filter in view

app.filter('domain', function () {
  return function (input) {
    var output = "",
    matches;

    var urls = /\w+:\/\/([\w|\.]+)/;
    matches = urls.exec( input );

    if (matches !== null) output = matches[1];
      return output;
  };
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: