PHP头条
热点:

看到PHP的一道面试题,做了上,不知道还有没好点方法


看到PHP的一道面试题, 做了下, 不知道还有没好点方法
题目如下,
类似这样的aaasssddd字符串,写个函数CutStr($str,$max)实现截取:
1)如果$max大于$str的长度则返回$str
2)不包含在长度计算范围。
例:
如果CutStr("aaasssddd",6) 则返回aaasss.
如果CutStr("aaasssddd",4) 则返回aaas,不包含标签

我的第一反应就是正则, 然后就...
var str = "aaasssddd";

function cutStr(str, max) {
    // 首先把先给剔除, 然后记录他们的位置
    var reg = new RegExp("(.*?)(.*?)(.*?)"); 
    var emSub = str.indexOf("");
    var em2Sub = str.indexOf("");
    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 是为了减去第一个占去的位置)
        var tempReg = new RegExp("(\\w{" + emSub + "})(\\w*?)");
        return newstr.replace(tempReg, "$1$2");
    } else { // 大于六
        var tempReg = new RegExp("(\\w{" + emSub + "})(\\w{" + (em2Sub - emSub - 4) + "}?)(\\w*?)");
        return newstr.replace(tempReg, "$1$2$3");
    }
}

alert(cutStr(str, 7));?


觉得这个方法好笨, 有什么别的好点的方法吗?

想到了,, 原来这个这么简单,, 我把它想复杂了...

var str = "aaasssddd";  
  
function cutStr(str, max) {  
    var emSub = str.indexOf("");  
    var em2Sub = str.indexOf("");  
    // 如果不是数字或是负数, 或者大于字符长度, 直接返回原字符  
    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));  ?

www.phpzy.comtrue/phprm/24156.htmlTechArticle看到PHP的一道面试题,做了上,不知道还有没好点方法 看到PHP的一道面试题, 做了下, 不知道还有没好点方法 题目如下, 类似这样的aaa sss ddd字符串,写个函数CutStr($str,$max)实现截取: 1)如...

相关文章

PHP之友评论

今天推荐