Home>Article>Web Front-end> How to get the string length in javascript

How to get the string length in javascript

青灯夜游
青灯夜游 Original
2021-06-29 16:56:35 42942browse

Javascript method to get the length of a string: 1. Use the length attribute to get the length of the string by characters, the syntax is "string.length"; 2. Use charCodeAt() to get the length of the string by bytes.

How to get the string length in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

js Determine the length of a string by characters

The length attribute can read the length of the string. The length is in characters and this property is read-only.
Sample code:

Output result:

11 12

Note:

1. Use the length attribute to get the length. Each character, including spaces and punctuation marks, is counted. One character

2. In the length attribute, Chinese characters also default to one character

js determines the length of a string by bytes

The bytes supported in JavaScript include single-byte and double-byte types. Generally speaking, English and English symbols occupy 1 character, and Chinese characters and Chinese symbols occupy 2 characters.

Example 1:

charCodeAt(): The method returns the Unicode encoding of the character at the specified position. Its value is an integer between 0 - 65535.

Output result:

18

Example 2:

A Chinese character is 2 characters, and a Chinese symbol is two characters.

Output result: 12

Example 3:

Replace the double-byte character with two single-byte characters and get its characters Number

Run result: 12

Example 4:

Run result: 14

Example 5:

You can use regular expressions to determine whether a character is double bytes

 //20

[Related recommendations:javascript learning tutorial]

The above is the detailed content of How to get the string length 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