日期:2014-05-17 浏览次数:20742 次
var str = "aaa<em>sss</em>ddd";
function cutStr(str, max) {
// 首先把<em>和</em>先给剔除, 然后记录他们的位置
var reg = new RegExp("(.*?)<em>(.*?)</em>(.*?)");
var emSub = str.indexOf("<em>");
var em2Sub = str.indexOf("</em>");
var newstr = str.replace(reg, "$1$2$3");
// 如果不是数字或是负数, 或者大于字符长度, 直接返回原字符
if (!/^\d+$/.test(max) || max >= newstr.length) return str;
newstr = newstr.substring(0, max);
if (max <= emSub) { //小于三
return newstr;
} else if (max <= em2Sub - 4 && max > emSub) { // 大于三, 小于六时(注: -4 是为了减去第一个<em>占去的位置)
var tempReg = new RegExp("(\\w{" + emSub + "})(\\w*?)");
return newstr.replace(tempReg, "$1<em>$2");
} else { // 大于六
var tempReg = new RegExp("(\\w{" + emSub + "})(\\w{" + (em2Sub - emSub - 4) + "}?)(\\w*?)");
return newstr.replace(tempReg, "$1<em>$2</em>$3");
}
}
alert(cutStr(str, 7));?
var str = "aaa<em>sss</em>ddd";
function cutStr(str, max) {
var emSub = str.indexOf("<em>");
var em2Sub = str.indexOf("</em>");
// 如果不是数字或是负数, 或者大于字符长度, 直接返回原字符
if (!/^\d+$/.test(max) || max >= str.length - 9) return str;
else if(max > em2Sub-4) return str.substring(0, max + 9);
else if(max > emSub) return str.substring(0, max + 4);
else return str.substring(0, max);
}
alert(cutStr(str, 7)); ?