Home  >  Article  >  Web Front-end  >  How to calculate how many characters in a string in javascript

How to calculate how many characters in a string in javascript

青灯夜游
青灯夜游Original
2021-09-02 18:03:539125browse

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;}".

How to calculate how many characters in a string in javascript

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:

How to calculate how many characters in a string in javascript

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:

How to calculate how many characters in a string in javascript

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn