Home > Article > Web Front-end > How to calculate how many characters in a string in javascript
Methods for counting the number of characters in JS: 1. Use the length attribute of the string, the syntax "str.length"; 2. Use the "for...of" or "for...in" statement loop Traverse the array and count the number of traversals. The syntax is "for(var ch of str) {Count;}".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use the length attribute of the string
In JavaScript, use the length attribute of the string to read the length of the string. The length is in characters and this property is read-only.
var str = "String 类型长度"; //定义字符串 console.log(str.length); //返回11个字符
Output result:
Method 2: Use the for...of or for...in statement to loop through the array and perform statistical traversal The number of times is enough
var str = "String 类型长度!"; //定义字符串 var charCount = 0; for (var ch of str) { charCount++; } // for (var ch in str) { // charCount++; // } console.log(charCount); // output: 12
Output result:
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to calculate how many characters in a string in javascript. For more information, please follow other related articles on the PHP Chinese website!