Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How many times a character occurs in a string?

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

like image 400
Ruth Avatar asked May 25 '10 09:05

Ruth


People also ask

How many times a character occurs in a string JS?

My favorite way to count how many times a character appears in a String is str. split("x"). length - 1 , where str is the String and "x" is the character you are searching for. The way this work is that the "split" method in Javascript splits the String into an array of substrings.

How do you find the number of occurrences of a character in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you check if a character is repeated in a string JavaScript?

you can use . indexOf() and . lastIndexOf() to determine if an index is repeated. Meaning, if the first occurrence of the character is also the last occurrence, then you know it doesn't repeat.

How do I count the number of times a word appears in a string JavaScript?

One of the solution can be provided by the match() function, which is used to generate all the occurrences of a string in an array. By counting the array size that returns the number of times the substring present in a string.


2 Answers

You could remove any other character in the string and check the length:

str.replace(/[^a]/g, "").length 

Here it is counted how many as are in str. The RegExp is described below:

[ // Start Character Group ^ // Not operator in character group a // The character "a" ] // End character group 
like image 83
Gumbo Avatar answered Sep 19 '22 16:09

Gumbo


This counts a in below example:

str = "A man is as good as his word"; alert(str.split('a').length-1); 

If you want case insensitive you'd want something like

alert(str.split( new RegExp( "a", "gi" ) ).length-1); 

So that it grabs "A" and "a" ... "g" flag isn't really needed, but you do need the "i" flag

like image 36
Sarfraz Avatar answered Sep 22 '22 16:09

Sarfraz