仅当字符串不为null或为空时,才使用分隔符连接字符串 [英] Join strings with a delimiter only if strings are not null or empty

查看:49
本文介绍了仅当字符串不为null或为空时,才使用分隔符连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这感觉应该很简单,如果我在这里遗漏了一些东西,抱歉,但是我试图找到一种简单的方法来连接非空或非空字符串.

This feels like it should be simple, so sorry if I'm missing something here, but I'm trying to find a simple way to concatenate only non-null or non-empty strings.

我有几个不同的地址字段:

I have several distinct address fields:

var address;
var city;
var state;
var zip;

这些值是根据页面中的某些表单字段和其他js代码设置的.

The values for these get set based on some form fields in the page and some other js code.

我想在 div 中输出完整地址,以逗号+空格分隔,所以是这样的:

I want to output the full address in a div, delimited by comma + space, so something like this:

$("#addressDiv").append(address + ", " + city + ", " + state + ", " + zip);

问题是,这些字段之一或全部可能为空/空.

Problem is, one or all of these fields could be null/empty.

是否有任何简单的方法可以将这组字段中的所有非空字段联接在一起,而无需在将其添加到字符串之前检查每个字段的长度?

Is there any simple way to join all of the non-empty fields in this group of fields, without doing a check of the length of each individually before adding it to the string?

推荐答案

考虑

var address = "foo";
var city;
var state = "bar";
var zip;

text = [address, city, state, zip].filter(Boolean).join(", ");
console.log(text)

.filter(Boolean)(与 .filter(x => x)相同)删除所有虚假"值(空,未定义,空字符串等).如果您对空"的定义不同,则必须提供它,例如:

.filter(Boolean) (which is the same as .filter(x => x)) removes all "falsy" values (nulls, undefineds, empty strings etc). If your definition of "empty" is different, then you'll have to provide it, for example:

 [...].filter(x => typeof x === 'string' && x.length > 0)

将仅在列表中保留非空字符串.

will only keep non-empty strings in the list.

-

(过时的jquery答案)

(obsolete jquery answer)

var address = "foo";
var city;
var state = "bar";
var zip;

text = $.grep([address, city, state, zip], Boolean).join(", "); // foo, bar

这篇关于仅当字符串不为null或为空时,才使用分隔符连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆