Count Characters in String JavaScript
In this article, we will see how to length characters in string javascript. If we use the length function it also calculates the space, so we get the wrong count. So we should not use the length function. For example:
Example :
var str1= "Hello world";
document.write(str1.length); //11
Here, we have 10 characters in variable str1 but the length function returns 11. Because it calculates space. So, it is the wrong way to find characters. To find characters in the string, we need to use for loop statement and charAt() function.
Find character:
var str1= "Hello world";
var count=0;
for(var i=0; i<str1.length;i++){
if(str1.charAt(i) != " "){
count++;}
}
document.write(" The length of the character in string : ")
document.write(count); //10
Output:
- In the above code, we have created a variable count and assigned a value to 0, it is going to calculate the character length.
- Then we created for loop statement and it runs up to string length.
- Inside the loop, we check the character is not equal to (” “) space using charAt() function. If the condition is true “count” will increment. Whereas the condition is false “count” won’t increment.
- Finally, print the variable count, so it returns the correct character length in the string.