0

I have some text "lorem ipsum^^^text^^^testtext" that I want to split onto new lines. I'm using split to separate the text into an array like so:

var companySplit = this.company.split('^^^');

and I can output this like so:

$("#company").html(companySplit[0] + '<br />' + companySplit[1]);

However, In certain situations, there may not be 2 array items...There could be 3 or 4 for example. How can I display the array items separated by a line break regardless of the amount of items? I've tried using a loop but I'm unfamiliar with them so I had trouble getting it working.

5 Answers 5

1

To do a loop, you would basically write:

for(var i = 0, l = companySplit.length; i < l; i++) {
   $('#company')
       .append('<br/>')
       .append(companySplit[i]);
}

You may want to check the value of i to avoid inserting a break before the first item.

if(i > 0)
   $('#company').append('<br/>');
$('#company').append(companySplit[i]);

But in your case a simple join would be enough:

$('#company').html(companySplit.join('<br/>'));

Or, for that matter, a replace:

$('#company').html(this.company.replace(/\^\^\^/g, '<br/>'));
Sign up to request clarification or add additional context in comments.

1 Comment

the replace solution is perfect for what I'm trying to achieve. Much simpler, thanks!
1

Use a for() loop.

var result[] = this.company.split('^^^');
var out;
for(int i=0,j=result.length; i<j; j++) {
  out += result[i] + '<br />';}
$("#company").html(out);

Comments

0

Try this.

 var companySplit = this.company.split('^^^');
 var htmlContent="";
   for(int count=0;count<companySplit.length;count++)
   {
      htmlContent=htmlContent+companySplit[count] + '<br />'

   }
   $("#company").html(htmlContent);

Comments

0
var i=0;
$.each(companySplit,function(){

$("#company").html(companySplit[i] + '<br />' + companySplit[i+1]);
i++;

});

Comments

0
$.each(company.split('^^^'), function(index, value) { 
  $("#company").append(value+'<br/>');
});​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.