How to trim a string to N chars in Javascript?

前端 未结 8 1510
暗喜
暗喜 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

    Just another suggestion, removing any trailing white-space

    limitStrLength = (text, max_length) => {
        if(text.length > max_length - 3){
            return text.substring(0, max_length).trimEnd() + "..."
        }
        else{
            return text
        }
    
    0 讨论(0)
  • 2020-12-22 19:09

    I think that you should use this code :-)

        // sample string
                const param= "Hi you know anybody like pizaa";
    
             // You can change limit parameter(up to you)
             const checkTitle = (str, limit = 17) => {
          var newTitle = [];
          if (param.length >= limit) {
            param.split(" ").reduce((acc, cur) => {
              if (acc + cur.length <= limit) {
                newTitle.push(cur);
              }
              return acc + cur.length;
            }, 0);
            return `${newTitle.join(" ")} ...`;
          }
          return param;
        };
        console.log(checkTitle(str));
    
    // result : Hi you know anybody ...
    
    0 讨论(0)
提交回复
热议问题