Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append text to all values of javascript Array

Tags:

javascript

Basically, I need to convert a string

"23423,1616,3461743,1345" 

to a string

"<img src='23423'></img><img src='1616'></img><img src='3461743'></img><img src='1345'></img>

So far I have tried:

    var PhotoArray=JSONeventobject.Events[i].FileNameArray.split(","); // Just convert this string to array

    for (i = 0; i < PhotoArray.length; i++) {
        PhotoArray[i] = "<img src='"+PhotoArray[i]+"</img>";
    }


            var Photostring = PhotoArray.toString().replace(",", "")

But this causes my browser to crash. It makes sense to me :/

like image 254
TaylorMac Avatar asked Oct 26 '11 03:10

TaylorMac


2 Answers

Some terrible answers here. Try:

"1,2,3,4".split(",").map(function(a) { return "<foo>" + a + "</foo>"; }).join("");

Or with slightly more modern Javascript:

"1,2,3,4".split(",").map(a => `<foo>${a}</foo>`).join("");

Also please be aware of HTML injection.

like image 189
Timmmm Avatar answered Oct 29 '22 21:10

Timmmm


You need to make sure you close your image tag. Another thing that may cause the problem is that i is undefined. Does your browser give an error message?

var str = "23423,1616,3461743,1345";
var PhotoArray = str.split(",");
for ( var i = 0; i < PhotoArray.length; i++ ) {
    PhotoArray[i] = "<img src=\"" + PhotoArray[i] + "\"></img>";
}
str = PhotoArray.join("");
like image 39
Will Avatar answered Oct 29 '22 22:10

Will