How to trim a string to N chars in Javascript?

前端 未结 8 1513
暗喜
暗喜 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: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 ...
    

提交回复
热议问题