Automatically add URL/email link by shawl. Qiu to JavaScript strings
Note:
In fact, I have written at least 10 codes for automatically appending URL/Email links.
Until recently, I learned about JS xiaocheng and made a perfect Dom solution, but I can add links without errors.
But the problem always occurs. Although the DOM method can be used to add links without errors, the indent format is lost ....
This is fatal, so it overwrites a record that won't lose indentation.
This is a direct string processing, and errors may occur, but the error rate will be quite low.
Directory:
1. Dom appending URL/email link
2. append URL/email link to the string
Shawl. Qiu
2006-12-13
Http://blog.csdn.net/btbtd
1. Dom appending URL/email link
- <script type="text/javascript">
- //<![CDATA[
- onload=function(){
- var o_=document;
- fDomAtcLink(o_.body, o_);
- }
- //sqMethod.attachlink(o_.body, o_)
- function fDomAtcLink(obj, dcu){
- var temp, str='', span;
- for(var i=0, j=obj.childNodes.length; i<j; i++){
- temp=obj.childNodes[i];
- if(temp.nodeType==3){
- if(temp.parentNode.nodeName=='A')return false;
- if(temp.data.indexOf('http')<0&&temp.data.indexOf('ftp')<0&&
- temp.data.indexOf('@')<0)continue;
- span=dcu.createElement('span');
- str=temp.data.replace(//&/g,'&').replace(/</g,'<').replace(/>/g,'>');
- //str=sqMethod.encode(temp.data);
- str=str.replace(/(ht|f)tp(s|)/:////[/-/w.:]+(//[^ /n/r/'/"]+|)/gi,function(match){
- return '<a href="'+match+'" class="sqUrl">'+match+'</a>'; } );
- str=str.replace(/[/w.]+@[/w/-.]+(//[^ /n/r/'/"]+|)/gi,function(match){
- return '<a href="mailto:'+match+'" class="sqMail">'+match+'</a>'; } );
- span.innerHTML=str;
- obj.replaceChild(span, temp);
- }
- if(temp.nodeType==1)arguments.callee(obj.childNodes[i], dcu);
- } temp=span=null; // shawl.qiu script
- }
- //]]>
- </script>
2. append URL/email link to the string
- <script type="text/javascript">
- //<![CDATA[
- onload=function(){
- var html=document.body.innerHTML;
- document.body.innerHTML=fPadUrl(document.body.innerHTML);
- document.body.innerHTML=fPadEmail(document.body.innerHTML);
- }
- function fPadUrl(str){
- if(!str||str.replace(//s+/,'').length<0)return false;
- var re=new RegExp('([//s//S]|)((ht|f)t(p|ps)/:////.*?)(//s|/ /;|/>/;|/</;|'+
- '[/'/"<>]|/&/#34/;)','gi');
- return str.replace(re,
- function($1,$2,$3,$4,$5,$6){
- if(//'|/"|/=|/= /.test($2))return $1;
- $3='<a href="'+$3+'" class="sqLink">'+$3+'</a>';
- return $2+$3+$6;
- }
- ); // shawl.qiu script
- }
- function fPadEmail(str){
- if(!str||str.replace(//s+/,'').length<0)return false;
- var re=new RegExp('(mailto/:|/>|)([//w/./-]+)/@(.*?)'+
- '(//s|/ /;|/>/;|/</;|[/'/"<>]|/&/#34/;)','gi');
- return str.replace(re,
- function($1,$2,$3,$4,$5){
- if(/mailto|>/.test($2))return $1;
- $3='<a href="mailto:'+$3+'@'+$4+'" class="sqLink">'+$3+'@'+$4+'</a>';
- return $2+$3+$5;
- }
- ); // shawl.qiu script
- }
- //]]>
- </script>