简体   繁体   English

用JavaScript / jQuery中的活动超链接替换粘贴的链接

[英]Replacing pasted links with active hyperlinks in JavaScript / jQuery

For my chat I need a jquery or javascript function that translates pasted links like http://example.com to active links like <a href="http://example.com">http://example.com</a> 对于我的聊天,我需要一个jquery或javascript函数,将粘贴的链接(如http://example.com为活动链接(如<a href="http://example.com">http://example.com</a>

Frankly I'm still quite bad with Regular Expressions (they somethimes looks like names of bohemian villages ;-)) and therefore I need your help. 坦白说,我对正则表达式仍然很不满意(它们的某些主题看起来像波希米亚村庄的名称;-),因此我需要您的帮助。 I'd like to translate the following PHP function into JavaScript / jQuery 我想将以下PHP函数转换为JavaScript / jQuery

function addHyperlinks($text){
    return  preg_replace(
     array(
       '/(?(?=<a[^>]*>.+<\/a>)
             (?:<a[^>]*>.+<\/a>)
             |
             ([^="\']?)((?:https?|ftp|bf2|):\/\/[^<> \n\r]+)
         )/iex',
       '/<a([^>]*)target="?[^"\']+"?/i',
       '/<a([^>]+)>/i',
       '/(^|\s)(www.[^<> \n\r]+)/iex',
       '/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)
       (\\.[A-Za-z0-9-]+)*)/iex'
       ),
     array(
       "stripslashes((strlen('\\2')>0?'\\1<a href=\"\\2\">\\2</a>\\3':'\\0'))",
       '<a\\1',
       '<a\\1 target="_blank">',
       "stripslashes((strlen('\\2')>0?'\\1<a href=\"http://\\2\">\\2</a>\\3':'\\0'))",
       "stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\">\\0</a>':'\\0'))"
       ),
       $text
   );       
}

I added already the following functions to my Javascript library to make replaceAll available. 我已经在Javascript库中添加了以下函数,以使replaceAll可用。

String.prototype.replaceAll = function(search, replace)
{
    if(!replace) 
        return this;

    return this.replace(new RegExp(escapeRegExp(search), 'g'), replace);
};

function escapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

I'm almost sure there is some function like this out there already, but I can't find it. 我几乎可以肯定已经有类似的功能了,但是我找不到。

Thanks, for pointing me in the right direction @waldek_c 谢谢你为我指出正确的方向@waldek_c

However to complete my question, here is the function I took adding the g parameter at the end of the exp variable 但是,为了完成我的问题,这是我在exp变量末尾添加g参数的函数

function replaceURLWithHTMLLinks(text) {
   var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
   return text.replace(exp,"<a href='$1'>$1</a>"); 
}

Thanks to this article: How to replace plain URLs with links? 感谢本文: 如何用链接替换纯URL?

Sorry for not having it found by myself :-) 很抱歉没有自己找到它:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM