Steve Spencer Steve Spencer - 2 months ago 23
Javascript Question

Replace links in javascript

I have this page that displays links from news sites. Everything works fine except for on one news site my links are followed by

,[object%20Object]


which makes the link unusable. How can I strip that away?
I would like the links that are generated to look like this:

www.example.com


Instead of like this:

www.example.com/,[object%20Object]


This is what I have:



<html>
<head>
<script>
function top_stories(o)
{
var items = o.query.results.item;
var output = '';
var no_items=items.length;
for(var i=0;i<no_items;i++)
{
var title = items[i].title;
var link = items[i].link;
var desc = items[i].description;
output += "<li><a href='" + link + "'>"+title+"</a></li>";
}
document.getElementById('results').innerHTML = output;
}
</script>
</head>
<body>
<div id='results'></div>
<script src='https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%3D%22http%3A%2F%2Ffeeds.feedburner.com%2Fbreitbart%22&format=json&diagnostics=true&callback=top_stories'>
</script>
</body>
</html>





And here is a link to the page http://sspencer10.com/test.html

Any help would be greatly appreciated!

Answer

The link property on the item is an array. You want link[0] which is the short URL of the item or link[1].href which is the actual URL.

function top_stories(o)
{
  var items = o.query.results.item;
  var output = '';
  var no_items=items.length;
  for(var i=0;i<no_items;i++)
    {
      var title = items[i].title;
      var link = items[i].link[1].href;
      var desc = items[i].description;
      output += "<li><a href='" + link + "'>"+title+"</a></li>";
    }
  document.getElementById('results').innerHTML = output;
}
Comments