morgi morgi - 3 months ago 8
Javascript Question

Replace displayed array commas with line breaks

I have this piece of code that fetches some links in

<li>
elements and then put their content into an array. Which works fine.

HTML

<ul id="links">
<li><a href="#" title="Open this form">Test 1</a></li>
<li><a href="#" title="Open this form">Test 2</a></li>
<li><a href="#" title="Open this form">Test 3</a></li>
</ul>

<div id="temporary-pool"></div>


JS

var links = [];

$("#links li").each(function() {
var rawLinks = $(this).html()
var textLinks = rawLinks.replace(/<a\b[^>]*>/i,"").replace(/<\/a>/i, "");

links.push(textLinks);
});

console.log(links);

$("#temporary-pool").html(
'<textarea id="clean-links">'
+links+
'</textarea>'
);


However, I would like to display the content in a
<textarea>
. When I simply print it, it obviously outputs as:

Test 1,Test 2,Test 3


What I would like, is for it to output the result as:

Test 1
Test 2
Test 3


I tried playing around with regex (I believe I need to replace "," with " ") but not successfully.

Answer

This should do it:

$("#temporary-pool").html(
    '<textarea  id="clean-links">'
        +links.join("\n")+
    '</textarea>'
);

You can find more info about join(...) HERE

And to simplify the other part of your code, you can do something like this:

$("#links li").each(function() {
   links.push($(this).text());
});

Info about jQuery.text() HERE

Comments