Convert generic text string in json object into valid url using Angular

- 1 answer

Ad

This is my first Stack Overflow question so bear with me (I almost always find what I need or figure it out myself but this time is different since I'm just getting my feet wet with Angular).

I have a directive the grabs the name and url from a json object and builds the html with the name and an href. The problem is, the json response from the url object is a regular text string entered by a user from a CMS and and it's currently not being validated on the backend. Therefore, the URL can look like www.blah.xxx or http://blah.xxx and so on. Is there an Angular way without using a plugin where I can tell the output to check that the url has http:// and if it doesn't then add it? Or is there a good plugin that will do the trick easily?

angular.module('pwrApp')
    .directive("getPrimaryCareProviderName", [function() {
        return {
            restrict: "A",
            link: function(scope, elem, attrs) {

            scope.$watch('primaryCareProvider', function() {
              var output = "";

                if(scope.primaryCareProvider.site == "" || scope.primaryCareProvider.site ===null){
                    output = scope.primaryCareProvider.name;
                }else{
                    output = '<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="'+scope.primaryCareProvider.url+'" target="_BLANK">'+scope.primaryCareProvider.name+"</a>";
                }

                elem.html(output);
            });
        }
    }
}]);
Ad

Answer

Ad

You can simply check every time if it's contains already the http in the beginning of the url:

 if(scope.primaryCareProvider.site == "" || scope.primaryCareProvider.site ===null){
           output = scope.primaryCareProvider.name;
     }
     else{
           var url = scope.primaryCareProvider.url
           if (url.indexOf("http://") != 0){
              url = "http://" + url;
           }
           output = '<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="'+url+'" target="_BLANK">'
                    +scope.primaryCareProvider.name+'</a>';
     }

But if you want a more sophisticated way, check this snippet

Ad
source: stackoverflow.com
Ad