How to get the string length in javascript

青灯夜游
Release: 2023-01-07 11:41:18
Original
42956 people have browsed it

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:

Copy after login

Output result:

11 12
Copy after login

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.

Copy after login

Output result:

18
Copy after login

Example 2:

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

Copy after login

Output result: 12

Example 3:

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

Copy after login

Run result: 12

Example 4:

Copy after login

Run result: 14

Example 5:

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

 //20
Copy after login

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

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!