Search code examples
javascriptjqueryimagerssfeed

Replace JSON encoded feed value's image src protocol http: with https:


I have a site on https protocol that is consuming via ajax JSONP a wordpress rss feed by google load feed API, and then iterating thru the returned json object to inject content

The issue is that the content node has html i would like to include, such as images that the poster inserted:

  "Title":"post title",
  "Content":"<p><img src='http://theothersite.com'/> this is an example post</p>"

When i iterate through the json using each(), the content html gets appended, and throws the browser an insecure content warning, because image src is of http protocol

 $.each(json.responseData.feed.entries, function(arrayID, News) {
 for(var i = 0; i < News.categories.length; i++)
 {
  html = '<li class="post news"><h3><a target="_blank" href="'+News.link+'">'+News.title+'</a></h3>';
  // HERES WHERE ATTENTION NEEDED
  html +='<div class="excerpt">'+News.content+'</div></li><hr>';

 $("#newsList ul").append(html);

I cant figure out how to parse the node content's value for src, and replace any src with a new src that has https as the protocol, while retaining all other string data

I have tried match, which worked fine to get the src into a variable, but it didnt take the rest of the string, so when i replaced it didnt retain the content

  var iMatches = News.content.match(/src=\"(.+?)\"/igm);  //alert(iMatches);
  if (iMatches) { 
    News.content.replace(/src=\"http:(.+?)\"/igm, /src=\"https:(.+?)\"/igm);}

I also tried the replace as replace('http:', 'https:') but that didnt work either

As always, any help appreciated


Solution

  • The String.replace method doesn't change the original string, it instead returns a new string. With that in mind, you need to use:

    News.content = News.content.replace(...);
    

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace