Noor
Noor

Reputation: 241

How can one put together multiple arrays into one string?

I'm having a hard time describing what I'm looking for.

If we pretend that we're pulling an array (I've used the .split to get user input data) where each line represents a link.

How can I then add an anchor tagg to that link that I'm pulling?

I need to be able to put

< a href=" + thearray + ">anything< /a>.

The reason for this is that I'm dynamically creating a list.

I think that if I create two variables, one with this part

< a href="

one with the closing and then call some sort of function that puts those two and the pulled array in between them until the list is complete.

Does this make any sense?

edit: here's a link to the full code: http://hem.bredband.net/noor/thecode.txt

Upvotes: 1

Views: 394

Answers (4)

clahey
clahey

Reputation: 4843

I think using map and then join is going to be more readable:

function makeLink(url)
{
   return "<a href=\"" + url + "\">anything</a>";
}
result = myArray.map(makeLink).join("\n");

More info about map is available at http://www.tutorialspoint.com/javascript/array_map.htm

Upvotes: 0

awgy
awgy

Reputation: 16914

Perhaps you mean something like this:

var tagStart = '<a href="',
    tagEnd = '">anything</a>',
    html = tagStart + thearray.join(tagEnd + tagStart) + tagEnd;

I would still suggest using a loop, though, since the code above will be unkind if thearray is empty.

Upvotes: 0

Jacob Mattison
Jacob Mattison

Reputation: 51052

Do you mean that you want to have an array like

["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"]

and you want to turn it into

"<a href='http://www.google.com'>anything</a>
<a href='http://www.yahoo.com'>anything</a>
<a href='http://www.stackoverflow.com'>anything</a>"

?

If so, you can just do

var myArray = ["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"];
var result = "";
for (var i=0; i<myArray.length; i++) {
   result += "<a href='" + myArray[i] + "'>anything</a>";
}

If not, thinking about "I want to start with X and end up with Y", with specific examples, might help you clarify your question.

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

I think you mean this:

for(var x=0;x<thearray.length;x++) {
   document.write '<a href=" + thearray[x] + ">anything</a>'
}

You just want to loop through the array elements, wrapping them in some HTML.

Upvotes: 2

Related Questions