string 仅当字符串不为 null 或为空时才使用分隔符连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19902860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:10:06  来源:igfitidea点击:

Join strings with a delimiter only if strings are not null or empty

javascriptstring

提问by froadie

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;

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

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

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

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

$("#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?

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

回答by georg

Consider

考虑

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

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

.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(Boolean)(与 相同.filter(x => x))删除所有“虚假”值(空值、未定义、空字符串等)。如果您对“空”的定义不同,那么您必须提供它,例如:

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

will only keep non-empty strings in the list.

只会在列表中保留非空字符串。

--

——

(obsolete jquery answer)

(过时的jquery答案)

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

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

回答by aga

Yet another one-line solution, which doesn't require jQuery:

另一个单行解决方案,不需要jQuery

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

text = [address, city, state, zip].filter(function (val) {return val;}).join(', ');

回答by Tim Santeford

Lodashsolution: _.filter([address, city, state, zip]).join()

Lodash解决方案:_.filter([address, city, state, zip]).join()

回答by tikhpavel

Just:

只是:

[address, city, state, zip].filter(Boolean).join(', ');

回答by Alexander Abakumov

@aga's solutionis great, but it doesn't work in older browsers like IE8 due to the lack of Array.prototype.filter()in their JavaScript engines.

@aga 的解决方案很棒,但由于其 JavaScript 引擎中缺少Array.prototype.filter(),因此它在 IE8 等较旧的浏览器中不起作用。

For those who are interested in an efficient solution working in a wide range of browsers (including IE 5.5 - 8) and which doesn't require jQuery, see below:

对于那些对在各种浏览器(包括 IE 5.5 - 8)中工作且不需要 jQuery 的高效解决方案感兴趣的人,请参见下文:

var join = function (separator /*, strings */) {
    // Do not use:
    //      var args = Array.prototype.slice.call(arguments, 1);
    // since it prevents optimizations in JavaScript engines (V8 for example).
    // (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
    // So we construct a new array by iterating through the arguments object
    var argsLength = arguments.length,
        strings = [];

    // Iterate through the arguments object skipping separator arg
    for (var i = 1, j = 0; i < argsLength; ++i) {
        var arg = arguments[i];

        // Filter undefineds, nulls, empty strings, 0s
        if (arg) {
            strings[j++] = arg;
        }
    }

    return strings.join(separator);
};

It includes some performance optimizations described on MDN here.

它包括MDN描述的一些性能优化这里

And here is a usage example:

这是一个使用示例:

var fullAddress = join(', ', address, city, state, zip);

回答by Arun P Johny

Try

尝试

function joinIfPresent(){
    return $.map(arguments, function(val){
        return val && val.length > 0 ? val : undefined;
    }).join(', ')
}
$("#addressDiv").append(joinIfPresent(address, city, state, zip));

Demo: Fiddle

演示:小提琴

回答by nicb

$.each([address,city,state,zip], 
    function(i,v) { 
        if(v){
             var s = (i>0 ? ", ":"") + v;
             $("#addressDiv").append(s);
        } 
    }
);`