JavaScript to automatically detect url address and add url link sample code

  • 2020-03-29 23:40:46
  • OfStack

Background: Write a simple chat system, issued Htpp Url implementation jump with a tag.
Implementation code:
String.prototype.httpHtml = function(){ 
var reg = /(http://|https://)((w|=|?|.|/|&|-)+)/g; 
return this.replace(reg, '<a target=_blank href="$1$2">$1$2</a>'); 

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

"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 | = | \? | \. | \ | and | -) +)/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.

When it comes to substitution in JavaScript, the first thing that comes to mind is the replace property. The power of the replace property is that it supports regular expressions that can be used to replace strings that conform to the rule. For example, if we want to replace Spaces on both ends of a string, we can use something like this:
var s = " blank "; 
s = s.replace(/^s+(.*?)s+$/, ""); 

Related articles: