The implementation of automatic addition of URL addresses actually consists of just that: detection and replacement.
Detection
"Detection" is to detect whether there is content in the text (string) that matches the http address. Obviously, this requires the use of regular expressions for verification. This work can be done by both the front-end and the back-end. Here, only the front-end method is discussed , implemented using JavaScript.
The regular expression to verify the HTTP address is as follows (there may be omissions or inaccuracies, please correct me):
The first part matches the URL string address starting with http or https, the latter part matches some characters, English characters, underscore (_), period (.), question mark (?) and equal sign (=), connecting short lines (-)wait.
Replace www.jb51.net
When it comes to the replacement function in JavaScript, the first thing that comes to mind is naturally the replace attribute. The power of the replace attribute is that it supports regular expressions and can replace strings that conform to regular expressions. . For example, if we want to replace the spaces at both ends of the string, we can use a statement similar to the following:
will get "blank", and the spaces at both ends will be removed. Similarly, just replace the matching http address with the http address containing the href attribute nested in the tag
For example, this expression can match URL addresses of http, https, ftp, ftps and IP addresses.
The URL address matching calculation is relatively complete. Using this expression, I wrote two small functions to replace the URL address of the user's message with a clickable link. There is nothing too difficult. Just use JavaScript's replace() function to replace the URL with link:
var replaceURLToLink = function (text) {
text = text.replace(URL, function (url) {
var urlText = url;
if (!url.match('^https?: //')) {
url = 'http://' url;
return text;
};