We usually use the length function to calculate the character length in js. However, it is strange to read the document written by a friend below, the following describes how to calculate the length of a null character or a string.
You can use the following three methods to calculate the string length:
The Code is as follows: |
Copy code |
Echo "$ str" awk '{print length ($0 )}' Expr length "$ str" Echo "$ str" wc-c |
However, if the value obtained in the third method is 1 more, the terminator may be included.
There are three methods to judge whether a string is null:
The Code is as follows: |
Copy code |
If ["$ str" = ""] If [x "$ str" = x] If [-z "$ str"]
|
Note: Double quotation marks must be replaced. Otherwise, some commands may report errors!
I didn't understand the above code, but I used
Core code:
The Code is as follows: |
Copy code |
Var jmz = {}; Jmz. GetLength = function (str ){ /// <Summary> obtain the actual length of the string, Chinese 2, and English 1 </summary> /// <Param name = "str"> string to be obtained </param> Var realLength = 0, len = str. length, charCode =-1; For (var I = 0; I <len; I ++ ){ CharCode = str. charCodeAt (I ); If (charCode> = 0 & charCode <= 128) realLength + = 1; Else realLength + = 2; } Return realLength; }; Run the Code: Alert (jmz. GetLength ('test ceshiceshi )); |
The judgment character is null.
The Code is as follows: |
Copy code |
Function empty (v ){ Switch (typeof v ){ Case 'undefined': return true; Case 'string': if (trim (v). length = 0) return true; break; Case 'boolean': if (! V) return true; break; Case 'number': if (0 = v) return true; break; Case 'object ': If (null = v) return true; If (undefined! = V. length & v. length = 0) return true; For (var k in v) {return false;} return true; Break; } Return false; } |
Additional usage
Typeof usage
The number of typeof operations is undefined, and "undefined" is returned ".
Number of operations: number typeof (x) = "number"
String typeof (x) = "string"
Boolean value typeof (x) = "boolean"
Object, array, and null typeof (x) = "object"
Function typeof (x) = "function"
(2) Determine if Javascript is empty
The Code is as follows: |
Copy code |
Var exp = null; If (! Exp & typeof (exp )! = "Undefined" & exp! = 0) { Alert ("is null "); } |
However, in DOM applications, we generally only need to use (! Exp) to determine, because in the DOM application, null may be returned, undefined may be returned, if the specific judgment of null or undefined will make the program too complex.