xzegga xzegga - 4 months ago 23
AngularJS Question

How I can extract image src from text in scope variable with angularjs

I have a portion of html code stored in a scope variable like this:

$scope.htmlcode = '<img src="image-path/image-name.jpg" /> some plain text,some plain text text etc etc';


I want to show only image src in html view like:

<div>image-path/image-name.jpg</div>

Answer

You can pull image strings out of a scope variable like this:

 //Embed Parsing + Lookup
 var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
 $scope.url_regex = new RegExp(expression);

 $scope.$watch('post_content', function(){

  if(!$scope.post_content){

  } else {
    var post_clone = $scope.post_content;
    var urls = post_clone.match($scope.url_regex);
    if(urls){
      var arrayLength = urls.length;
       if (arrayLength > 0){  
        console.log('We have media:' + urls[0]);
        $scope.checkOembed(urls[0]);
      }
    } else {
      console.log('NO URLS in $scope.post_content');
    }
  }
}, true);