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.
Thanks, for pointing me in the right direction @waldek_c
However to complete my question, here is the function I took adding the g
parameter at the end of the exp
variable
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?
Sorry for not having it found by myself :-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.