Reputation: 213
I'm trying to complete this exercise, returning an array with the hashtags used, but I'm only able to return "#" instead of the whole str[i]. What am I doing wrong?
This is my code so far:
function extractHashtags(str) {
let solution = [];
for(let i=0; i<str.length; i++){
if(str[i].startsWith('#')){
solution.push(str[i]);
}
}
return solution;
}
AssertionError: expected [ '#' ] to deeply equal [ '#yolo' ]
+ expected - actual
[
- "#"
+ "#yolo"
]
Trying to find out how to do it, came across this and I've also tried it this way:
function extractHashtags(str) {
let solution = [];
solution.push(str.match(/[^#]/g));
return solution;
}
But still doesn't work. I suppose the most elegant way is using regex, but I'm more than lost with it. Anyone can give me a hand? Thanks for your help!
Upvotes: 0
Views: 485
Reputation: 370679
See
solution.push(str[i]);
You're only pushing the initial '#'
character - you want to push the whole word. Assuming tags are separated by spaces, you can try something like this instead:
const solution = str.split(' ').filter(word => word.startsWith('#'));
Upvotes: 2