Hi this question needed to be deleted
Asked
Active
Viewed 7,011 times
5 Answers
2
You can use string#split and then use map to get the length of each word.
let string = 'pineapple and black bean curry',
result = string.split(/\s+/).map(({length}) => length);
console.log(result)
Hassan Imam
- 20,493
- 5
- 36
- 47
1
I changed .split() to .split(' ') and len.push(words[i]) to len.push(words[i].length).
const text = 'pineapple and black bean curry'; //[9, 3, 5, 4, 5]
function getWordLengths(str) {
let len = [];
let words = str.split(' ');
for (let i = 0; i < words.length; i++){
len.push(words[i].length);
}
return len;
}
console.log(getWordLengths(text));
holydragon
- 4,911
- 4
- 30
- 45
0
\b in a regex expression to split words.
let line='pineapple and black bean curry';
let results=line.match(/\b[^\s]+?\b/g).map(r=>r.length);
console.log(results)
lx1412
- 1,042
- 5
- 13
0
There are quite a few ways to do this buddy.
- The simplest way would probably be to do as you attempted, i.e., to use the
.split()feature. It works only when used rightly. You have forgotten to split the string based on a separator. And here since you are interested in individual words, the separator should be a space.' '. just map the lengths of the words onto a new array and print it out.
let string = 'pineapple and black bean curry';
let words = string.split(' ');
console.log(words.map(word => word.length))
- If you don't want to use
maporsplitfunctionalities and want to do it using straightforward manual ways, you can do the following: In this , you just keep a counter variable which you increment as long as you don't encounter a space or end of the string and then reset it at the start of the next word.
let string = 'pineapple and black bean curry';
let count = 0, count_array = [];
let x = string.length;
for(i=0;i<=x;i++){
if(string[i]==' ' || string[i]=='\0' || i==x){
count_array.push(count);
count=0;
}
else{
count++;
}
}
console.log(count_array);
Harshith Rai
- 2,958
- 7
- 20
- 35