The implementation of automatic adding of URL addresses is actually something: Detection and replacement.
Detection
"Detection" is to check whether the text (string) contains content that conforms to the http address. Obviously, this requires regular expression verification. This can be done at the front end and back end. Here, only the front-end method is used for implementation in JavaScript.
The regular expression used to verify the HTTP address is as follows (which may be incorrect or inaccurate ):
Copy codeThe Code is as follows:
Var reg =/(http: // | https: //) (w | = |? |. |/| & |-) +)/G;
The first part matches the URL string address starting with http or https. The latter part matches some characters, including English characters, underscores (_), periods (.), and question marks (?) And equal signs (=), short connections (-), etc.
Replace www.jb51.net
When it comes to the replacement function in JavaScript, the first thing that comes to mind is the replace attribute. The powerful feature of the replace attribute is that it supports regular expressions and can replace regular strings. For example, to replace the spaces at both ends of a string, you can use a statement similar to the following:
Copy codeThe Code is as follows:
Var s = "blank ";
S = s. replace (/^ s + (.*?) S + $ /,"");
Alert (s );
"Blank" is obtained, and spaces at both ends are removed. Similarly, you only need to replace the matched http address with the http address containing the href attribute nested in the <a> tag.
For example, this expression can match the URL addresses of http, https, ftp, ftps, and IP addresses.
Copy codeThe Code is as follows:
Var URL =/(https? : // | Ftps? ://)? (D {1, 3}. d {1, 3}. d {1, 3}. d {3}) (: [0-9] + )? | ([W] +.) (S +) (w {2, 4}) (: [0-9] + )?) (/? ([W #! :.? + = & % @! -/] + ))? /Ig;
It is still well-regarded for URL address matching. Using this expression, I wrote two small functions to replace the URL address of the user's message with the clickable link. Nothing is too difficult, that is, using the replace () of JavaScript () function to replace the URL with link:
Copy codeThe Code is as follows:
/**
* JavaScrit version
* Convert the URL address to the complete A tag link code
*/
Var replaceURLToLink = function (text ){
Text = text. replace (URL, function (url ){
Var urlText = url;
If (! Url. match ('^ https? ://')){
Url = 'HTTP: // '+ url;
}
Return ''+ urlText + '';
});
Return text;
};