I have this situation where I have to get or calculate how many characters are in multiple strings. Example:
var aText = Array(
"There are only 2 types of people in the world:",
"Girls and boys, any other thing? i don't know.");
There’s more than 80 characters in both strings combined. Another note is that, the strings may not be fixed as they may increase or decrease. Is there a way I can do this in JavaScript?
I tried using aText.length
but this only returned how many strings where in the variable. Which in this case is only 2.
4
Answers
You can use a simple forEach loop to loop through the array and get the length of each element in the array.
However, you still need to do something with the length. In this case I’m just showing it in the console.
I added a variable that shows the total number of characters in the array.
This is how I would do it.
Use
String.length
to get the length of each item andArray.reduce()
to compute the sum of the lengths:Yes, you can. To find length of characters in all strings that are inside array you can use
array.join('').length
.join(”) concatenates all the strings in the array together into a single string with no separator between them. After that .length property is used to count total number of characters in the resulting string.
Check this example: