admin管理员组文章数量:1129075
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.
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?
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.
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?
Share Improve this question edited Nov 1, 2018 at 22:18 Alexander Abakumov 14.5k16 gold badges96 silver badges132 bronze badges asked Nov 11, 2013 at 9:27 froadiefroadie 82.9k78 gold badges170 silver badges236 bronze badges 1- Why not have all those fields in an object then loop, compare, discard? – elclanrs Commented Nov 11, 2013 at 9:28
7 Answers
Reset to default 473If your definition of "empty" means falsy values (e.g., null
s, undefined
s, empty strings, 0
, etc), consider:
var address = "foo";
var city;
var state = "bar";
var zip;
text = [address, city, state, zip].filter(Boolean).join(", ");
console.log(text)
.filter(Boolean)
is the same as .filter(x => Boolean(x))
.
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.
(obsolete jquery answer)
var address = "foo";
var city;
var state = "bar";
var zip;
text = $.grep([address, city, state, zip], Boolean).join(", "); // foo, bar
Yet another one-line solution, which doesn't require jQuery
:
var address = "foo";
var city;
var state = "bar";
var zip;
text = [address, city, state, zip].filter(function(val) {
return val;
}).join(', ');
console.log(text);
Lodash solution: _.filter([address, city, state, zip]).join()
@aga's solution is great, but it doesn't work in older browsers like IE8 due to the lack of Array.prototype.filter() in their JavaScript engines.
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:
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.
And here is a usage example:
var fullAddress = join(', ', address, city, state, zip);
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
$.each([address,city,state,zip],
function(i,v) {
if(v){
var s = (i>0 ? ", ":"") + v;
$("#addressDiv").append(s);
}
}
);`
Here's a simple, IE6 (and potentially earlier) backwards-compatible solution without filter
.
TL;DR → look at the 3rd-last block of code
toString()
has a habit of turning arrays into CSV and ignore everything that is not a string, so why not take advantage of that?
["foo", null, "bar", undefined, "baz"].toString()
→ foo,,bar,,baz
This is a really handy solution for straightforward CSV data export use cases, as column count is kept intact.
join()
has the same habit but let's you choose the joining delimiter:
['We built', null, 'this city', undefined, 'on you-know-what'].join('
本文标签:
javascriptJoin strings with a delimiter only if strings are not null or emptyStack Overflow
版权声明:本文标题:javascript - Join strings with a delimiter only if strings are not null or empty - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:http://www.betaflare.com/web/1736735557a1950234.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论