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>
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
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.
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.