If you only want to count the non-whitespace characters in a string, you can use the .trim() method before checking the .length property. This will remove any leading or trailing whitespace from the string, which will result in a more accurate character count.
This last one replaces all non-letter characters with an empty string, then counts the resulting string. Note that this will not work for non-Latin alphabets.
Split string into array using regex
You can also use a regular expression to split a string into an array of characters, which can then be counted using the .length property.
This iterates over each character in the string and increments a counter. Note that this method is not supported in IE8 and earlier versions.
If you need to support older browsers, you can use a for loop:
var str = "Hello world!";
This approach can be slightly more tedious, but it can also be more accurate as you have more control over what counts as a character.
In addition, this method can also be used to count characters in any type of data, not just strings.
You can also use this method to count the number of properties in an object.