Display only 10 characters of a long string?

前端 未结 12 2087
臣服心动
臣服心动 2020-12-13 01:19

How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery?

Sorry guys I\'m a novice at JavaScript & JQuery :S

12条回答
  •  一生所求
    2020-12-13 01:49

    Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.

    Ternary operator will sort that out:

    var text = "blahalhahkanhklanlkanhlanlanhak";
    var count = 35;
    
    var result = text.slice(0, count) + (text.length > count ? "..." : "");
    

    Can be closed to function:

    function fn(text, count){
        return text.slice(0, count) + (text.length > count ? "..." : "");
    }
    
    console.log(fn("aognaglkanglnagln", 10));
    

    And expand to helpers class so You can even choose if You want the dots or not:

    function fn(text, count, insertDots){
        return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
    }
    
    console.log(fn("aognaglkanglnagln", 10, true));
    console.log(fn("aognaglkanglnagln", 10, false));
    

提交回复
热议问题