JavaScript make a web url into a link using Regular Expression. A sample implementation in AngularJS

Regular expression are nothing but patterns which are matched with the given piece of text.

Sample Code: 

var replacedText, replacePattern1, replacePattern2, replacePattern3;
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = text.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return $sce.trustAsHtml(replacedText);

Demo:

Here is a sample implementation to convert a given text into a link,

Make URLs into Links using Regular Expression- AngularJS

Printed as TEXT: {{data.string | linkfy}}

Printed as HTML:

Example:
<html>
<head>
    <title>Make URLs into Links using Regular Expression- AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp" ng-controller="myController">
        <input id="updateval" type="text" stye="width:200px; height:30px; padding: 5px; margin: 15px 0;" placeholder="Enter any URL Here..." ng-model="data.string">
        <br/>
        <div><span>Printed as TEXT: </span><span>{{data.string | linkfy}}</span></div>
        <br/>
        <div><span>Printed as HTML: </span><span ng-bind-html="data.string | linkfy"></span></div>
    </div>
 
    <script> 
         var myApp = angular.module("myApp", []);
         myApp
         .filter('linkfy', function ($sce) {
            return function (text) {
              var replacedText, replacePattern1, replacePattern2, replacePattern3;
              replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
              replacedText = text.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
              replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
              replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
              replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
              replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
              return $sce.trustAsHtml(replacedText);
            };
          })
          .controller('myController', function($scope) {
            $scope.data = {
               string: '',
            };
         });
      </script>
</body>
</html>
Category: