This article mainly introduces examples of the length of characters intercepted by byte in JS. If you need it, refer *
* Process long strings, intercept and add ellipsis
* Note: The halfwidth is 1 and the fullwidth is 2.
*
* PStr: String
* PLen: truncation Length
*
* Return: the truncated string.
*
The Code is as follows:
Function autoAddEllipsis (pStr, pLen ){
Var _ ret = cutString (pStr, pLen );
Var _ cutFlag = _ ret. cutflag;
Var _ cutStringn = _ ret. cutstring;
If ("1" = _ cutFlag ){
Return _ cutStringn + "...";
} Else {
Return _ cutStringn;
}
}
*
* Obtain a string of the specified length.
* Note: The halfwidth is 1 and the fullwidth is 2.
*
* PStr: String
* PLen: truncation Length
*
* Return: the truncated string.
*
The Code is as follows:
Function cutString (pStr, pLen ){
// Original String Length
Var _ strLen = pStr. length;
Var _ tmpCode;
Var _ cutString;
// By default, the returned string is part of the original string
Var _ cutFlag = "1 ";
Var _ lenCount = 0;
Var _ ret = false;
If (_ strLen <= pLen/2 ){
_ CutString = pStr;
_ Ret = true;
}
If (! _ Ret ){
For (var I = 0; I <_ strLen; I ++ ){
If (isFull (pStr. charAt (I ))){
_ LenCount + = 2;
} Else {
_ LenCount + = 1;
}
If (_ lenCount> pLen ){
_ CutString = pStr. substring (0, I );
_ Ret = true;
Break;
} Else if (_ lenCount = pLen ){
_ CutString = pStr. substring (0, I + 1 );
_ Ret = true;
Break;
}
}
}
If (! _ Ret ){
_ CutString = pStr;
_ Ret = true;
}
If (_ cutString. length = _ strLen ){
_ CutFlag = "0 ";
}
Return {"cutstring": _ cutString, "cutflag": _ cutFlag };
}
*
* Determine if it is full
*
* PChar: A string with a length of 1
* Return: tbtrue: fullwidth
* False: halfwidth
*
The Code is as follows:
Function isFull (pChar ){
For (var I = 0; I <pChar. strLen; I ++ ){
If (pChar. charCodeAt (I)> 128 )){
Return true;
} Else {
Return false;
}
}
}
Use Case:
The Code is as follows:
TestStr = "Test 1 string ";
AutoAddEllipsis (testStr, 1); // "test ..."
AutoAddEllipsis (testStr, 2); // "test ..."
AutoAddEllipsis (testStr, 3); // "test ..."
AutoAddEllipsis (testStr, 4); // "test ..."
AutoAddEllipsis (testStr, 5); // "Test 1 ..."
AutoAddEllipsis (testStr, 6); // "Test 1 ..."
AutoAddEllipsis (testStr, 7); // "Test 1 word ..."