Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get string length by javascript

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report