我发现这个很棒的代码可以将纯文本链接到链接......
function text_to_link(inputText)
{
/*var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1' target='_blank'>$1</a>");*/
var replaceText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with www. (without // before it, or it'd re-link the ones done above)
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links
replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
}
现在代码很棒,但它损害了嵌入式对象和iframe ......
<object width="300" height="182"><param name="movie" value="http://www.youtube.com/v/xVaBIF1LnwY?fs=1&hl=en_GB"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/xVaBIF1LnwY?fs=1&hl=en_GB" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object>
它还会占用文本中的所有br /(换行符)......
示例页面here
我们可以只编码它以保留“对象和对象”或“iframe和iframe”中的所有文本
由于
答案 0 :(得分:0)
有一个标准的解决方案:
首先在对象和iframe标签内“编码” inputText 的出现,以便http | ftp | www | @。这样,在步骤2中不会替换这些序列。
按照原始功能进行更换。
现在“解码”http | ftp | www | @的出现。
的Jakub
答案 1 :(得分:0)
我可以某种方式使用它...但不是一个好的解决方案...
function text_to_link(inputText)
{
var object_text = new Array();
var oi = 0;
while ( inputText.indexOf('<object') >= 0)
{
var si = inputText.indexOf('<object');
var ei = inputText.indexOf('</object>');
object_text[oi] = inputText.substring(si,ei+9);
inputText = inputText.replace(object_text[oi] , '[ob_service]');
oi ++;
}
var iframe_text = new Array();
var ii = 0;
while ( inputText.indexOf('<iframe') >= 0)
{
var si = inputText.indexOf('<iframe');
var ei = inputText.indexOf('</iframe>');
iframe_text[ii] = inputText.substring(si,ei+9);
inputText = inputText.replace(iframe_text[ii] , '[if_service]');
ii ++;
}
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
inputText = inputText.replace(exp,"<a href='$1' target='_blank'>$1</a>");
oi =0;
while (inputText.indexOf('[ob_service]') >= 0)
{
inputText = inputText.replace('[ob_service]' , object_text[oi]);
oi ++;
}
ii =0;
while (inputText.indexOf('[if_service]') >= 0)
{
inputText = inputText.replace('[if_service]' , iframe_text[ii]);
ii ++;
}
return inputText;
}
任何知道正则表达式的人都能做些好事......
由于