How to trim a string to N chars in Javascript?

前端 未结 8 1508
暗喜
暗喜 2020-12-22 18:09

How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument. For example:

var strin         


        
8条回答
  •  有刺的猬
    2020-12-22 18:50

    Copying Will's comment into an answer, because I found it useful:

    var string = "this is a string";
    var length = 20;
    var trimmedString = string.length > length ? 
                        string.substring(0, length - 3) + "..." : 
                        string;
    

    Thanks Will.

    And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

提交回复
热议问题