I have an input in which I can type tags separated by comma. Said input can receive a string in this way:
hola, hello, hola hello, , hola,
The string is then sent to the backend of my app in this way:
req.body.tags.split(',').map((tag) => tag.trim())
This only helps to split the string by commas
string1, string2
That's great but what if I had a string as the one shown below:
string1, string2, , string4
How can I ignore or remove the empty 'object' between the commas after string2 and the comma after string4?. Not only that, what if I had a string that looks similar to the first one I mentioned before?
string1, string2, , string4, string5,
Let's not forget about the spaces(which I would like to replace with a hyphen):
string1, string2, , string4, string 5, string6,
How would I ignore the empty object after the last comma also?
I'm asking because this is how it usually looks on my mongoDB after the data is sent:
tags: [
"string1",
"string2",
"",
"string4",
"string5",
""
]
I'm just trying to avoid having empty objects.
UPDATE ONE:
req.body.tags.split(',').map((tag) => tag.trim()).filter((tag) => tag.length !== 0)
It works great. With that being said, I still need to replace the spaces with hyphens. I tried this and did not work:
req.body.tags
.split(',')
.map((tag) =>
tag
.trim()
.replace(/[\s]+/g, '-')
.toLowerCase()
)
.filter((tag) => tag.length !== 0)