Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to get string length by javascript

Shulou Source: shulou.com Published: 2022-05-31 11:51:19 09月15日 Update

This article introduces the knowledge of "how to get the string length of javascript". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Javascript gets the string length: 1, use the length attribute to get the string length by character, syntax "string .length"; 2, use charCodeAt () to get the string length by byte.

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

Js judges the length of a string by character

The length property reads the length of the string. The length is in characters, and the attribute is read-only.

Sample code:

Var str = 'hello wordsman; console.log (str.length); var str2 =' Hello, World! Hello, China!' ; console.log (str2.length)

Output result:

11 12

Note:

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

2. In the length attribute, the Chinese character defaults to one character.

Js judges 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 account for 1 character, while Chinese characters and Chinese symbols account for 2 characters.

Example 1:

CharCodeAt (): the method returns the Unicode encoding of the characters at the specified position. Its value is an integer between 0 and 65535.

Var str = 'movie: me and my motherland'; var len = 0; for (var I = 0; I

< str.length; i++) { if (str.charCodeAt(i) >

| | str.charCodeAt (I) = = 94) {len+ = 2;} else {len++;}} console.log (len)

Output result:

eighteen

Example 2:

One Chinese character has two characters, and one Chinese symbol has two characters.

Var str = 'Hello, World!' ; var len = 0; for (var I = 0; I

< str.length; i++) { var c = str.charCodeAt(i); //单字节加1 if ((c >

= 0x0001 & & c

Tags: Character length string byte attribute example result symbol Chinese output Hello expression World two content method more regular knowledge Chinese character Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux OPPO Reno Huawei Xiaomi Shulou Tech Info