Gordian
Gordian

Reputation: 258

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.

Upvotes: 2

Views: 118

Answers (2)

Joe
Joe

Reputation: 47619

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:

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.

Upvotes: 4

Reyraa
Reyraa

Reputation: 4274

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;
  };
});

Upvotes: 2

Related Questions