views:

48

answers:

2

The situation:

On server A we want to display content from server B in line on server A.

The problem:

Some of the hyperlinks in the content on server B are relative to server B which makes them invalid when displayed on server A.

Given a block of HTML code that contains anchor tags like the following

<a href="/something/somwhere.html">Somewhere</a>

what would be the most efficient way to convert them to

<a href="http://server-b.com/something/somewhere.html"&gt;Somewhere&lt;/a&gt;

There can be multiple anchor tags in the content, the one catch is that some might be absolute and I want to leave those as they are, I only want to prepend the domain of server B to the relative URLs

+2  A: 

I wouldn't do this in Java; I like to handle view-specific logic in the view layer. I'm assuming this block of code is coming from an AJAX call. So what you can do is get the HTML from the AJAX call and then do this:

jQuery(html).find("a[href]").each(function(index, value) {
  var $a = jQuery(value);
  var href = $a.attr("href");

  if(!/^http:/.test(href)) {
     $a.attr("href", "http://server-b.com" + href);
   }
});

Or if you really want to do this in Java, Lauri's answer will work.

Vivin Paliath
Thanks, although this was a Javascript solution it worked well for me.
Flash84x
+1  A: 

Depending on a lot of things around how your web app is set up, and also on your definition of efficient, this might not be what you need or are looking for. But anyway, if you have your HTML as a String (in some late stage of a Filter for example), you could do something like this:

html = html.replaceAll("href=\"/", "href=\"http://server-b.com/")
Lauri Lehtinen