-2

N00b here! I have addresses where each part needs to be on a separate line. But if there's nothing in the Address line_2 or Address line_3, then don't insert a line break. How do I go about doing this?

My javascript:

var html = "<b>" +first +"\xa0" +last +"</b> <br/>" + line_1 +"<br/>" 
+ line_2 +"<br/>"
+ line_3 +"<br/>" 
+ city +"\xa0" + state +"\xa0" +zipcode;

Thank you in advance!

Erik Onyski
  • 3
  • 1
  • 3

2 Answers2

1

You can use the ternary operator, it is a condensed if where

var result = (if this is true) ? 'return this' : 'if not return this';

In your case, something like this

var html = "abc" + (line_2 == '' ? '' : line_2 + '<br>') + "xyz";
Juank
  • 6,096
  • 1
  • 28
  • 28
0

Use (line_2 ? line_2 +"<br/>" : "") which only adds the line_2 if defined and not null or else adds an empty string.

var html = "<b>" +first +"\xa0" +last +"</b> <br/>" + line_1 +"<br/>"
+ (line_2 ? line_2 +"<br/>" : "")
+ (line_3 ? line_3 +"<br/>" : "")
+ city +"\xa0" + state +"\xa0" +zipcode;

console.log(html);
Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17