views:

28

answers:

3

I have the following code for javascript:

function append_place(street, city, state, country) {
      var address = street + ', ' + city + ', ' + state + ', ' + country;
      $(".shop_location").append(address);

street, city, state, country are external variables drawn from database. (I'm working on Ruby on Rails project by the way.)

Ideally, when all values are found from the database, the output in HTML will be:

<div class="shop_location">3 Spencer St, Melbourne, Victoria, Australia</div>

But, when state has no value in the database, the output in HTML will be:

<div class="shop_location">3 Spencer St, Melbourne, , Australia</div>

How do I write in Javascript that when a value is empty, it will be replaced by some other value, or even better, omit it. Ideal output when state has no value is:

<div class="shop_location">3 Spencer St, Melbourne, Australia</div>

For some other function, I may want to display "Not available" if the value is not found.

Of course in Ruby on Rails I can just use an if-else statement in my view to replace the text.

Many thanks!

A: 

What about:

function append_place(street, city, state, country) {
  var a = new Array();
  if (street.length > 0) a.push(street);
  if (city.length > 0) a.push(city);
  if (state.length > 0) a.push(state);
  if (country.length > 0) a.push(country);

  var address = a.join(', ');
  $(".shop_location").append(address);
}
Scott Stafford
+1  A: 

I don't know about javascript, but I often do this sort of thing in a rails helper:

[street, city, state, country].compact.join(', ')

If the entries are nil, that works, but if there is a blank string "", then use this:

[street, city, state, country].reject(&:blank?).join(', ')
DGM
A: 

Keeping it simple:

function append_place(street, city, state, country) {
      var address = street + ', ' + city + ', '
      if (state) {
           address += state + ', ';
      }
      address += country;
      $(".shop_location").append(address);
mjhm