JS How to create a function that count the number of hashtags

Viewed 609

This question has been deleted

3 Answers

A simple loop does it. Since you're using ES2015+ syntax, a for-of would work nicely:

function countHashtagsAndMentions(str) {
  let hashtags = 0;
  let mentions = 0;
  for (const ch of str) {
    if (ch === "#") {
      ++hashtags;
    } else if (ch === "@") {
      ++mentions;
    }
  }
  return {hashtags, mentions};
}
let str = "So excited to start  @coding on Monday! #learntocode #codingbootcamp";
console.log(countHashtagsAndMentions(str));

That works because strings are iterable in ES2015+. The for-of loop implicitly uses the iterator from the string to walk through its characters. So within the loop, ch is each character from the string. Note that unlike str.split(), a strings iterator doens't separately the two halves of a character that requires a surrogate pair (like most emojis), which is normally what you want.

This:

for (const ch of str) {
    // ...
}

is effectively the same as

let it = str[Symbol.iterator]();
let rec;
while (!(rec = it.next()).done) {
    const ch = rec.value;
    // ...
}

but without the it and rec variables.


Alternately, you could use replace with a regular expression to replace all characters other than the ones you want to count. It sounds like it would be more expensive, but it's something the JavaScript engine can optimize:

function countHashtagsAndMentions(str) {
  return {
    hashtags: str.replace(/[^#]/g, "").length,
    mentions: str.replace(/[^@]/g, "").length
  };
}
let str = "So excited to start  @coding on Monday! #learntocode #codingbootcamp";
console.log(countHashtagsAndMentions(str));

Which you use probably depends in part on the length of the string. The replace option is nice and short, but does go through the string twice.

You could use an object for checking and counting.

function countHashtagsAndMentions(str) {
    var result = { '#': 0, '@': 0 },
        i;

    for (i = 0; i < str.length; i++) {
        if (str[i] in result) ++result[str[i]];
    }
    return result;
}

var str = "So excited to start  @coding on Monday! #learntocode #codingbootcamp";

console.log(countHashtagsAndMentions(str));

Use Array#reduce

const message = "So excited to start @coding on Monday! #learntocode #codingbootcamp"

const res = message.split("").reduce((acc,cur)=>{
  
  if('#@'.includes(cur)){
    const key = cur === '#' ? 'hashtags' : 'mentions';
    acc[key] = acc[key] + 1;

  }
  
  return acc;
}, {mentions: 0, hashtags: 0})

console.log(res);

Related