开发者

Replace variable value with plain text or ignore it if value is not available

开发者 https://www.devze.com 2023-01-22 17:24 出处:网络
I have the following code for javascript: function append_place(street, city, state, country) { var address = street + \', \' + city + \', \' + state + \', \' + country;

I have the following code for javascript:

function append_place(street, city, state, country) {
      var address = street + ', ' + city + ', ' + state + ', ' + country;
      $(".sh开发者_JS百科op_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!


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(', ')


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消