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