Count Number of Occurrences of a Character

Is there a way to count the number of occurrences of a specific character within a string?

For example, I have a string of text (it happens to be in a repeater, but I think that’s not critical to this question) “dog, cat, cassowary,” and I’d like to count how many commas appear in the string. In this case the answer would be three.

It seems like there ought to be a function like string.count(",") that would return 3 … but I have not found such a thing.

Thank you!
Jacque

Count the occurrences of 4:

[['123444'.length - '123444'.replace('4','').length]]

We’re subtracting the length of the string with the target character removed from the length of the complete string. The resulting difference is the number of characters that were removed, which is the number of times that character occurred.

You could replace the literal string with a variable, and even make the target character a variable too:

[[someString.length - someString.replace(someCharacter,'').length]]
3 Likes

Veeeeeeeery clever. Wish I could say I had thought of it. Will try implementing in a moment.

Thanks for the reply & help!
Jacque

Yep, that did it, thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.