[英]How to avoid empty objects in array from string separated by comma using JavaScript and NodeJS?
我有一个输入,我可以在其中键入用逗号分隔的标签。 所述输入可以通过这种方式接收字符串:
hola, hello, hola hello, , hola,
然后以这种方式将字符串发送到我的应用程序的后端:
req.body.tags.split(',').map((tag) => tag.trim())
这仅有助于用逗号分隔字符串
string1, string2
这很好,但如果我有一个如下所示的字符串怎么办:
string1, string2, , string4
如何忽略或删除 string2 之后的逗号和 string4 之后的逗号之间的空“对象”? 不仅如此,如果我有一个看起来与我之前提到的第一个字符串相似的字符串怎么办?
string1, string2, , string4, string5,
让我们不要忘记空格(我想用连字符替换):
string1, string2, , string4, string 5, string6,
我怎么会忽略最后一个逗号后的空 object 呢?
我问是因为这是发送数据后在我的 mongoDB 上通常的样子:
tags: [
"string1",
"string2",
"",
"string4",
"string5",
""
]
我只是想避免有空的对象。
更新一:
req.body.tags.split(',').map((tag) => tag.trim()).filter((tag) => tag.length !== 0)
它工作得很好。 话虽如此,我仍然需要用连字符替换空格。 我试过这个并没有用:
req.body.tags
.split(',')
.map((tag) =>
tag
.trim()
.replace(/[\s]+/g, '-')
.toLowerCase()
)
.filter((tag) => tag.length !== 0)
您可以使用filter
function 从数组中删除空字符串。
const tags = 'hola, hello, hola hello, , hola,'; const res = tags.split(',').map((tag) => tag.trim()).filter((tag) => tag.length;== 0). console;log(res);
如果要替换数组的字符串项中的所有空格,可以按如下方式进行。
const tags = 'ho la, hello, hola hello, , hola,'; const res = tags.split(',').map((tag) => tag.trim().replace(/[\s]+/g, '-').toLowerCase()).filter((tag) => tag.length;== 0). console;log(res);
您可以过滤数组中的空字符以防止这种情况发生。
var sparseArray = [0, , , 1, , , , , 2, , , , 3], cleanArray = sparseArray.filter(function () { return true }); console.log(cleanArray); // [ 0, 1, 2, 3 ]
在此处查看完整帖子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.