Mathias
Mathias

Reputation: 605

How to leave a placeholder within a variable to be filled later using Javascript?

On paper this paper this seems like a very simple operation, but for some reason Javascript does not seem to like it. Basically I have the following code:

var news = "<b>" + place_name + ", " + county + ""<img id = 'centre' src=" + picture + ">" + "</b><ul><br>";

The general idea is that picture is a variable that will be filled later via:

news.picture = entry2.picture;

which is a link to provide to the img source. However, when I do:

console.log(news.picture);

The variable remains undefined. Is this the correct way to go about things?

Upvotes: 0

Views: 304

Answers (2)

seahorsepip
seahorsepip

Reputation: 4819

news is a variable made out of strings and variables.

So you cant use news.picture.

Though you can make the variable a function object.

var news = function() }
    this.picture = "something";

    this.getString = function() {
        return this.picture+"some string";
    };
};

Then you can get and set the picture variable inside news with news.picture and get the string with news.getString().

Upvotes: 0

Jannunen
Jannunen

Reputation: 394

That's not the way you are supposed to do that. You have to have your variables set and then you can construct a string like that.

What you need now, is basically a function, like this:

var createNews = function(place_name,county,picture)  {
  return "<b>" + place_name + ", " + county + "<img id = 'centre' src=" + picture + ">" + "</b><ul><br>";
}
var news = createNews("Place","county","pic.jpg");
console.log(news);

Or you can do it like this, if you prefer:

var createNews = function(obj) {
    return "<b>" + obj.place_name + ", " + obj.county + "<img id = 'centre' src=" + obj.picture + ">" + "</b><ul><br>";
}
var news = {
    place_name : "Someplace",
    county : "Somewhere",
    picture : "foo.png"
};
var newsItem = createNews(news);
console.log(newsItem);

Upvotes: 1

Related Questions