我怎么能,使用Javascript,使一个函数,将修剪字符串传递作为参数,到指定的长度,也作为参数传递。例如:

var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);

// trimmedString should be:
// "this is"

有人有想法吗?我听说过一些关于使用子字符串,但不太明白。


当前回答

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

从链接:

string.substr(start[, length])

其他回答

这是我的解决方案,其中也包括修剪空白。

const trimToN = (text, maxLength, dotCount) => {
  let modText = text.trim();

  if (modText.length > maxLength) {
    modText = text.substring(0, maxLength - dotCount);
    modText = modText.padEnd(maxLength, ".");

    return modText;
  }

  return text;
};

trimToN('Javascript', 6,2)将返回“Java..”

有几种方法可以做到这一点

let description = "your test description your test description your test description";
let finalDesc = shortMe(description, length);

function finalDesc(str, length){

// return str.slice(0,length);

// return str.substr(0, length);

// return str.substring(0, length);

}

您还可以修改此函数以进入字符串之间。

只是另一个建议,删除任何尾随空白

limitStrLength = (text, max_length) => {
    if(text.length > max_length - 3){
        return text.substring(0, max_length).trimEnd() + "..."
    }
    else{
        return text
    }

首选String.prototype.slice而不是String.prototype.substring方法(在substring中,在某些情况下它给出的结果与您期望的结果不同)。

从左到右修剪字符串:

const str = "123456789";
result = str.slice(0,5);     // "12345", extracts first 5 characters
result = str.substring(0,5); // "12345"

startIndex > endIndex:

result = str.slice(5,0);     // "", empty string
result = str.substring(5,0); // "12345" , swaps start & end indexes => str.substring(0,5)

从右到左修剪字符串:(-ve start index)

result = str.slice(-3);                 // "789", extracts last 3 characters
result = str.substring(-3);             // "123456789" , -ve becomes 0 => str.substring(0)
result = str.substring(str.length - 3); // "789"

我认为你应该使用这个代码:-)

    // 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 ...