javaScript文字截取
开发过程当中,有时会遇到截取问题,主要是文字长度问题。
要截取的字符串中可能存在空格,可能存在英文,可能存在中文。如果你的字符串是来自富文本那就更有意思了,里面会存在标签。
情况多变,如果只用普通字符串截取的话,就会存在显示长短不一的情况
例如:
解决这种问题最好的办法就是,转义,将空格,特殊字符,或者标签先转换。
例如:
一串儿字符中存在标签:1.前台创建一个隐藏的Text,2然后用js或者后台把你的字符串赋值给这个Text,然后读取这个Text的值,这个时候标签已经被转换,你读取的已经是一个字符串了
剩下的就是中英文转换来进行截取了
var sub = function (str, n) { var r = /[^\x00-\xff]/g; if (str.replace(r, "mm").length <= n) { return str; } var m = Math.floor(n / 2); for (var i = m; i < str.length; i++) { if (str.substr(0, i).replace(r, "mm").length >= n) { return str.substr(0, i) + "..."; } } return str; }
var GetLength = function (str) { ///<summary>获得字符串实际长度,中文2,英文1</summary> ///<param name="str">要获得长度的字符串</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; };
function Bind_Icmskoo_Post(CateID) { var HtmlAppend = ""; $("#PostCateId_87").html(""); var cateidVal = CateID; $.ajax({ type: "get", cache: false, contentType: "application/json; charset=utf-8", url: "PublickAjax.ashx", data: { Type: 'Bind_EnterpriseDynamics', r: Math.random(), CateId: cateidVal }, success: function (data) { if (data != null && data != "") { var tempdata = eval('(' + data + ')').Table; HtmlAppend += " <div role='tabpanel' class='tab-pane active' id=''>"; HtmlAppend += " <div class='row'>"; //便利出数据 $.each(tempdata, function (name, value) { HtmlAppend += "<div class='col-sm-4' onclick='GovernmentFieldUrl(" + cateidVal + "," + value.PostId + ")'>"; HtmlAppend += "<a href='javascript:void(0)' class='tab-c' onclick='GovernmentFieldUrl(" + cateidVal + "," + value.PostId + ")'>"; HtmlAppend += "<figure>"; HtmlAppend += "<img src='" + value.Image + "' width='100%' onclick='GovernmentFieldUrl(" + cateidVal + "," + value.PostId + ")'>"; HtmlAppend += "</figure>"; HtmlAppend += "<div class='tab-txt' onclick='GovernmentFieldUrl(" + cateidVal + "," + value.PostId + ")'> "; HtmlAppend += "<p class='tab-tt' onclick='GovernmentFieldUrl(" + cateidVal + "," + value.PostId + ")'>" + value.PostTitle + "</p>"; $("#PostCateId_87Text").html(value.PContent); var PContentVal = $("#PostCateId_87Text").text(); if (GetLength(PContentVal) > 100) { PContentVal = sub(PContentVal, 100); } HtmlAppend += " <p class='tab-article' onclick='GovernmentFieldUrl(" + cateidVal + "," + value.PostId + ")'>" + PContentVal + "</p>" HtmlAppend += "</div>"; HtmlAppend += "</a>"; HtmlAppend += "</div>"; }); HtmlAppend += " </div></div>"; $("#PostCateId_87").append(HtmlAppend); } } }); }