How to trim a string to N chars in Javascript?

前端 未结 8 1552
暗喜
暗喜 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 19:08

        let trimString = function (string, length) {
          return string.length > length ? 
                 string.substring(0, length) + '...' :
                 string;
        };
    

    Use Case,

    let string = 'How to trim a string to N chars in Javascript';
    
    trimString(string, 20);
    
    //How to trim a string...
    

提交回复
热议问题