I need to count letters of string, I don't know how to count an empty array
const regex = /[\[\]]/gi;
const a = str.replaceAll(regex, ' ').trim().split(" ")
const arr = []
const arr2 = []
let newArr
for(let i = 0; i < a.length; i++) {
if (a[i].length === 0) {
arr2.push(0)
}
if (a[i].length !== 0) {
arr.push(a[i].length)
}
}
newArr = arr.concat(arr2)
if (newArr.includes(0)) {
newArr.pop()
}
return newArr.join(", ")
I must get: [Tom][] -> 3, 0 But I get a 3 without zero
It's not described in the question text, but according to your code, the input string has the format: (\[[a-zA-Z]*\])*.
I would remove the first [ and the last ]. Then, I would split the string by ][.
const str = '[Tom][]';
const substrs = str.substring(1, str.length - 1).split('][');
const lengths = substrs.map(str => str.length);
console.log(lengths.join(', '));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With