Is there a way to count the number of certain characters in a string?

For example : how many occurrences of the characters 'a', '?', '<' In the drain "Hello, are you here ??".

Itself, while only with regular expressions, works, (right? Or is there another way?):

var my_text = document.getElementById('myTextArea'); var result = my_text.value.match(/[a\?\<]/g).length; 

Everything is processed by onkeyup when typing, will accept any of your comments.

  • And the cycle will not be easier? Write a function and run a string through it. - Sugar
  • and what doesn’t suit you my_text.value.match(/[a\?\<]/g).length; ? all other methods will be perverted, for example: my_text.split (''). filter (function (a) {return ['a', '?', '<']. indexOf (a)> - 1;}). length - zb '11
  • one
    Look at the benchmarks of jsperf.com/split-vs-regexp-in-search-entries solutions - zb '11
  • on chrome like this the fastest: my_text.match (/ a | \ <| \? / g) .length - zb '11
  • @eicto Your option cannot be faster in principle. It can only be slower due to the regular expression device. - ReinRaus

1 answer 1

 ("Hello, are you here??".split("a").length - 1); 
  • > how many occurrences of characters {'a', '?', '<'} in the drain "Hello, are you here ??" - michael
  • one
    "Hello, are you here??".split(/[a\?\<]/) - fori1ton
  • one
    How complicated. match returns an array, if the regular expression with the g modifier, it remains only to find the length of the array. - ReinRaus