* * handle long strings, intercept and add ellipses * note: the length of the half Angle is 1, and the length of the whole Angle is 2 * * pStr: string * pLen: intercept length * * return: the truncated string *
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;
}
}
* * gets a string of the specified length * note: the length of the half Angle is 1, and the length of the whole Angle is 2 * * pStr: string * pLen: intercept length * * return: the truncated string *
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};
}
* * to determine whether it is a full Angle * * pChar: a string of length 1 * return: tbtrue: full Angle * False: half Angle *
function isFull (pChar) {
for (var i = 0; i < pChar.strLen ; i++ ) {
if ((pChar.charCodeAt(i) > 128)) {
return true;
} else {
return false;
}
}
}
Use cases:
testStr = " test 1 string ";
autoAddEllipsis(testStr, 1); //"Test..."
autoAddEllipsis(testStr, 2); //"Test..."
autoAddEllipsis(testStr, 3); //"Test..."
autoAddEllipsis(testStr, 4); //"Test..."
autoAddEllipsis(testStr, 5); //"The test 1..."
autoAddEllipsis(testStr, 6); //"The test 1..."
autoAddEllipsis(testStr, 7); //"Test 1 word..."