Reputation: 3888
In javascript I have an array like
psi=["www.google.com","www.facebook.com","www.collegehumor.com"]
I want to turn it to a formatted string like
var final=<a href="www.google.com" target="_blank">www.google.com</a></br>,<a href="www.facebook.com" target="_blank">www.facebook.com</a></br>,<a href="www.collegehumor.com" target="_blank">www.collegehumor.com</a></br>
so I can send from server to client something like
//websockets, btw...
connection.send('Search Results'+t_name+'</br>Links'+final+'</br>');
and it will render just the working links.
Something like
www.google.com
www.facebook.com
www.collegehumor.com
I know there is the toString()
. But no luck with that. I cant make it create working links.
I tried to implement a for
inside the connection.send
but Dreamweaver says there is a syntax error. That's why I try to convert the array to formatted string.
Any advise?
Thanks
Upvotes: 1
Views: 4221
Reputation: 10838
var psi=["www.google.com","www.facebook.com","www.collegehumor.com"]
var str = '';
for(var i in psi)
{
str += ',<a href="http://'+psi[i]+'" target="_blank">'+psi[i]+'</a><br>';
}
str = str.substr(1);
Alternate version using the string.link()
method mentioned by Zim84 in the comments above:
var psi=["www.google.com","www.facebook.com","www.collegehumor.com"]
var str = '';
for(var i in psi)
{
var url = psi[i];
str += ','+url.link('http://'+url)+'<br>';
}
str = str.substr(1).replace('">','" target="_blank">');
Upvotes: 2
Reputation: 1000
If you are willing to use jQuery it's a piece of cake:
var final = $.map(psi, function(link) {
return '<a href="' + link + '" target="_blank">' + link + '</a>';
}).join('<br />,');
Upvotes: 0
Reputation: 4051
var final = "";
for (var i = 0; i < psi.length; i++)
{
var linkWithHttp = "http://" + psi[i];
final += "<a href=\"" + linkWithHttp + "\" target=\"_blank\">" + psi[i] + "</a><br />,";
}
// Remove the last "," if you added, at least, one element
if (psi.length > 0)
{
final = final.substring(0, final.length - 1);
}
// Now final is like what you want
// Send it using connection.send()
Upvotes: 1