Home > Web Front-end > JS Tutorial > JS code that counts the most occurrences of characters_javascript skills

JS code that counts the most occurrences of characters_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:14:50
Original
987 people have browsed it

Applying global matching of regular expressions can match the number of occurrences of a character, compare these times, and save and return the largest one. The code is as follows:

Copy code The code is as follows:

var countMost = function(str){
if(!str) return;
var _count = 0, _temp = 0, _reg, _char;
for(var i=0; i_reg = new RegExp(str.charAt(i), 'g');
_temp = str.match(_reg).length;
if(_temp > _count){
_count = _temp;
_char = str.charAt(i);
}
}
return _count;
//return {count:_count, char:_char};
};

The commented out code can also return the characters that appear the most times.
Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template