Javascript automatically adds links to text url addresses for method sharing

  • 2020-03-30 01:23:34
  • OfStack

The implementation of automatic URL address addition is just that: detection and replacement.

detection

"Detection" is to detect whether the text (string) is consistent with the content of the HTTP address, obviously, this requires the use of regular expressions to verify, this work can be done in the front and the background, here, only the front end of the method, using JavaScript.

The following regular expression is used to verify the HTTP address:


var reg = /(http://|https://)((w|=|?|.|/|&|-)+)/g;

The first part matches the URL string address starting with HTTP or HTTPS, and the second part matches some characters, such as English characters, underscore (_), dot (.), question mark (?). And the equal sign (=), connect the short line (-) and so on.


var s = " blank ";
s = s.replace(/^s+(.*?)s+$/, "");
alert(s);

You get "blank", and the Spaces on both ends are eliminated. Again, just replace the matching HTTP address with < A> A nested HTTP address with an href attribute in the tag will do

For example, this expression can match the URL addresses of HTTP, HTTPS, FTP, FTPS, and IP addresses.


var URL = /(https?://|ftps?://)?((d{1,3}.d{1,3}.d{1,3}.d{1,3})(:[0-9]+)?|([w]+.)(S+)(w{2,4})(:[0-9]+)?)(/?([w#!:.?+=&%@!-/]+))?/ig;

Also is the URL address matching algorithm perfect. Using this expression, I wrote two small functions to replace the URL address left by the user with a clickable link. Nothing is too difficult, just use the JavaScript replace() function to replace the URL as link:



var replaceURLToLink = function (text) {
        text = text.replace(URL, function (url) {
            var urlText = url;
            if (!url.match('^https?://')) {
                url = 'http://' + url;
            }
            return '' + urlText + '';
        });
        return text;
    };


Related articles: