+ 1
Write a javascript count occurrences of character in string
Write a javascript count occurrences of character in string
1 Réponse
0
You could either use .match():
var string1 = "abcdefghijk";
var stringCount1 = string1.match(/a/g).length;
stringCount1 will return a value of 1.
Or, you could use .split():
var string2 = "aaaaaaaa";
var stringCount2 = string2.split("a").length - 1;
stringCount2 will return a value of 8.
.match() is preferred, since it takes a shorter amount of time to process.