0

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
  • 28,421
  • 8
  • 67
  • 102
redfrogsbinary
  • 619
  • 5
  • 13
  • 26

5 Answers5

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,195
  • 1
  • 26
  • 57
0
iconBlue.image='http://www.site.com/icon'+iconspec+'.jpg';
Dan Kanze
  • 18,485
  • 28
  • 81
  • 134
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
  • 28,421
  • 8
  • 67
  • 102
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
  • 30,730
  • 8
  • 78
  • 73
0

You can do this using template literals:

iconBlue.image = `http://www.yoursitehere.com/icon${iconspec}.jpg`;

Inside the backticks `` you can use ${} with the variable name to use a variable in a string.

Jake L
  • 177
  • 1
  • 9