当前位置: 代码迷 >> JavaScript >> 施用javaScript进行字符截取
  详细解决方案

施用javaScript进行字符截取

热度:93   发布时间:2012-09-18 16:21:42.0
使用javaScript进行字符截取
//标题长度
var NEBarTitleLength = 26;
//导航标题的长度
var NavTitleLength = 128;

/*
 * 将指定的字符串加工为limit长度的字符,后面加"..."并返回。
 * str 要加工的字符串
 * limit 要限制的字节数
 * mustCut 是否必须截取字符串 true,false,主要用于公共组件里字符串的截取
 */
ps.string.cutString=function(str,limit,mustCut)
{
	if(limit != NavTitleLength && !mustCut){
		return str;
	}
	return baseCutString(str,limit);
};



var psCharCodeMap = {
		32:3,33:3,34:6,35:7,36:7,37:9,38:9,39:3,40:4,
		41:4,42:5,43:7,44:3,45:4,46:3,47:3,48:7,49:7,50:7,
		51:7,52:7,53:7,54:7,55:7,56:7,57:7,58:3,59:3,60:7,
		61:7,62:7,63:7,64:12,65:7,66:8,67:9,68:9,69:8,70:7,
		71:9,72:9,73:3,74:6,75:8,76:7,77:9,78:9,79:9,80:8,
		81:9,82:9,83:8,84:7,85:9,86:7,87:11,88:7,89:7,90:7,
		91:4,92:3,93:4,94:7,95:7,96:4,97:7,98:7,99:6,100:7,
		101:7,102:3,103:7,104:7,105:3,106:3,107:6,108:3,109:11,110:7,
		111:7,112:7,113:7,114:4,115:7,116:3,117:7,118:5,119:9,120:5,
		121:5,122:5,123:5,124:3,125:5,126:7
	};
/**
 * 按字符宽度来截取字符串
 * @param labelText
 * @param rowWidth
 * @returns
 */
function baseCutString(labelText, rowWidth) {
		rowWidth = rowWidth * 7-9;
		var l = 0,c = 0,i = 0,j = 0;
		for(; i<labelText.length; i++){
		        c = labelText.charCodeAt(i);
		        l += c < 255 ? (psCharCodeMap[c] || 7) : 13;
		        if(l > rowWidth && !j){
		            j = i-1;
		        }
		}
		return l <= rowWidth + 9 ? labelText : labelText.substring(0,j) + "...";
	}
  相关解决方案