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

How to calculate how many characters in a string in javascript

青灯夜游
Release: 2023-01-07 11:46:52
Original
9173 people have browsed it

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个字符
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template