[removed] How many times a character occurs in a string?

前端 未结 6 2087
傲寒
傲寒 2020-12-13 03:15

Is there a simple way to check how many times a character appears in a String?

6条回答
  •  借酒劲吻你
    2020-12-13 04:04

    In my opinion it is more convenient and safe to avoid regular expressions in this case

    It's because if we want to be able to count any kind of characters then we need to consider two expressions. One for common characters and second for special characters for example like [, ], ^ and so on. It's easy to forget about it, but even if we remember it, I think we're unnecessarily expanding our code.

    In this case for string str and character ch works each of these solutions:

    let count = str.split(ch).length - 1
    

    (thanks to @Sarfraz)

    or

    let count = str.split('').filter(x => x == ch).length
    

    or

    let count = 0
    str.split('').forEach(x => x == ch ? count++ : null)
    

    Enjoy!

提交回复
热议问题