-1

The following variable contains a string that is a path to an image.

iconBlue.image = 'http://www.site.com/icon1.jpg';

How can include a variable in this path? Let me explain more detailed. Lets say there are many icons in a folder icon1.jpg icon2.jpg etc. I have a variable named iconspec that depending on its value (1 or 2 or 3 etc) points to the icon I must use.

How can i include variable iconspec in the path?

iconBlue.image='http://www.site.com/icon"iconspec".jpg

Something like this i guess but with correct syntax.

David Hoerster
  • 27,923
  • 8
  • 65
  • 100
redfrogsbinary
  • 579
  • 5
  • 11
  • 26

4 Answers4

1

You just need to put it like a simple string with variable.

In your case, you should do this:

iconBlue.image = 'http://www.site.com/icon'+iconspec+'.jpg';

The + operator is like the . in PHP, it merge string.

Frederick Marcoux
  • 2,139
  • 1
  • 26
  • 56
0
iconBlue.image='http://www.site.com/icon'+iconspec+'.jpg';
Dan Kanze
  • 18,385
  • 28
  • 80
  • 133
0

To take a little different route, you could encapsulate the concatenation in a function and make it a bit more reusable:

var icon = function(){
    this.path = '';
    this.imageName = '';

    this.imagePath = function() { return this.path + '/' + this.imageName };
};


var iconBlue = new icon(),
    iconRed = new icon();
iconBlue.path = "c:\\stuff";
iconBlue.imageName = "icon1.jpg";

iconRed.path="c:\\morestuff";
iconRed.imageName = "icon2.jpg";

alert(iconBlue.imagePath());
alert(iconRed.imagePath());
David Hoerster
  • 27,923
  • 8
  • 65
  • 100
0

The simplest solution is to use the + to concatenate the variable to the string:

var name = 'sachleen';
var result = 'my name is ' + name;

Output: my name is sachleen

There are a couple of more powerful options available as well.

JavaScript sprintf() is a sprintf implementation for JS.

string.format in JS

Community
  • 1
  • 1
sachleen
  • 29,893
  • 8
  • 74
  • 71