1

Simply, I want to parse URL link(s) and add html reference using jQuery, RegEx.

Source HTML is:

<div id="test"> my favorite search engines are http://www.google.com 
    and http://stackoverflow.com Do you agree? </div>

My Current Script is:

var exp = /(^|[^'">])((ftp|http|https):\/\/(\S+))(\b|$)/gi;
$('#test').html($('#test').html().replace(exp,
    "&nbsp;<a href='$2' target='_blank'><img src='go.gif'/></a>"));
});

And its result is as following:

<div id="test"> my favorite search engines are 
<a href="http://www.google.com" target='_blank'>
<img src='go.gif'/></a> and
<a href="http://stackoverflow.com" target='_blank'>
<img src='go.gif'/></a>
Do you agree? </div>

I know this script just replaces and can't preserve its source. I'd like to add its original URL right after 'img tag'. Anyone has an idea to get following result?

<div id="test"> my favorite search engines are 
<a href="http://www.google.com" target='_blank'>
<img src='go.gif'/>http://www.google.com</a> and
<a href="http://stackoverflow.com" target='_blank'>
<img src='go.gif'/>http://stackoverflow.com</a>
Do you agree? </div>

Thank you for your comment in advance.

user2526472
  • 65
  • 1
  • 8

3 Answers3

1

This is the solution (you can test the regular expression here: http://regexr.com/)

var test = $('#test'),
    txt = test.html(),
    pattern = /((?:http|ftp|https):\/\/[\w\-_]+(?:\.[\w\-_]+)+(?:[\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)/gi;

test.html(txt.replace(pattern, '<a href="$1" target="_blank"><img src="go.gif"/>$1</a>'));

You can add some css:

#test a img { margin-right: 5px; }
jherax
  • 5,238
  • 5
  • 38
  • 50
0

Something like this:

var urlRE = /(^|[^'">])((ftp|http|https):\/\/(\S+))(\b|$)/gi;
var $test = $('#test');
var text = $test.text();

text = text.replace(urlRE, "<a href=\"$&\">$&</a>");

$test.html(text);

jsFiddle

SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59
0
$('#test').html($('#test').replace(regex, "a href=" ????));
//              ^^^^^^^^^^^^^^^^^^

won't work. You would need ….html($('#test').html().replace(…, but it's better to use the callback version of .html().

For the regex we'll just use "anything that starts with http://", you're free to refine that.

For the replacement, we could add an extra capturing group around the url, but we don't really need this to use a replacement pattern.

var regex = /http:\/\/\S+/g;
$('#test').html(function(i, markup) {
    return markup.replace(regex, '<a href="$&">$&</a>');
});

Oh, the question has changed substantially.

I know this script just replaces and can't preserve its source. I'd like to add its original URL right after 'img tag'.

You can just use the $2 replacement pattern twice. Btw, you just removed the first capturing group entirely and put &nbsp; instead, which can be incorrect. Better use

"$1<a href='$2' target='_blank'><img src='go.gif'/>$2</a>"
Bergi
  • 630,263
  • 148
  • 957
  • 1,375