The implementation of the URL address automatically adds that is actually the content: detection and replacement.
Test
"Detection" is to detect whether the text (string) has the content that meets the HTTP address. Obviously, this requires a regular expression to verify. This work can be done at the front and backstage. accomplish.
The regular expression of the verification of the HTTP address is as follows (there may be omissions or inaccurate, welcome to correct it):
Copy code code as follows:
var reg =/(http://|https://) ((w wroads wbo=||.......| && &-)+)/g;
The previous part matches the URL string address at the beginning of HTTP or HTTPS, and the latter part is matched with some characters, English characters, down lines (_), dot (.), Question marks (?), And equal number (=), connected to the short-term (-) wait.
Replace www.vevb.com
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 the regular string. For example, we need to replace the space at both ends of the string to use the following statement:
Copy code code as follows:
var s = "Blank";
s = s.replace (/^s+(.*?) s+$/, "");
alert (s);
It will get "Blank", and the space at both ends will be removed. Similarly, as long as the matching HTTP address is replaced with a <a> label nesting HREF -containing http address
For example, this expression can match the URL address of HTTP, HTTPS, FTP, FTPS, and IP addresses.
Copy code code as follows:
var url =/(https?: // | ftps ?:/)? [0-9]+)? | ([W]+.) (S+) (s+) (w {2,4}) (: [0-9]+)?) ([W#!:.?+ = &%@!-/]+)?/Ig;
It is still a complete URL address matching. I wrote two small functions with this expression and replaced the URL address of the user's message to a clickable link. There is nothing too difficult. It is to use the replace () function of JavaScript to realize the replacement of the URL LINK:
Copy code code as follows:
/**
* Javascrip version
* Convert the URL address to a complete A tag link code
*/
var replaceurstolink = Function (text) {
text = text.replace (url, function (url) {
var urltext = url;
if (! url.match ('^https?: //') {{
url = 'http: //' + url;
}
Return '' + urltext + '';
});
Return text;
};