简体   繁体   English

如何在 Javascript 中将字符串修剪为 N 个字符?

[英]How to trim a string to N chars in Javascript?

How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument.我如何使用 Javascript 制作一个 function 来修剪作为参数传递的字符串,使其达到指定的长度,也作为参数传递。 For example:例如:

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

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

Anyone got ideas?有人有想法吗? I've heard something about using substring, but didn't quite understand.我听说过一些关于使用 substring 的事情,但不是很明白。

Why not just use substring... string.substring(0, 7);为什么不直接使用子字符串... string.substring(0, 7); The first argument (0) is the starting point.第一个参数 (0) 是起点。 The second argument (7) is the ending point (exclusive).第二个参数 (7) 是终点(不包括)。 More info here. 更多信息在这里。

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

Copying Will's comment into an answer, because I found it useful:Will 的评论复制到答案中,因为我发现它很有用:

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/ :)对于任何关心https://jsfiddle.net/t354gw7e/ 的人来说,这是一个 jsfiddle :)

I suggest to use an extension for code neatness.我建议使用扩展来保持代码整洁。 Note that extending an internal object prototype could potentially mess with libraries that depend on them.请注意,扩展内部对象原型可能会干扰依赖它们的库。

String.prototype.trimEllip = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

And use it like:并像这样使用它:

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)

Little late... I had to respond.有点晚了......我不得不回应。 This is the simplest way.这是最简单的方法。

 // JavaScript function fixedSize_JS(value, size) { return value.padEnd(size).substring(0, size); } // JavaScript (Alt) var fixedSize_JSAlt = function(value, size) { return value.padEnd(size).substring(0, size); } // Prototype (preferred) String.prototype.fixedSize = function(size) { return this.padEnd(size).substring(0, size); } // Overloaded Prototype function fixedSize(value, size) { return value.fixedSize(size); } // usage console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"'); console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"'); console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"'); console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');

Step by step.一步步。 .padEnd - Guarentees the length of the string .padEnd - 保证字符串的长度

"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository." “padEnd() 方法用给定的字符串填充当前字符串(重复,如果需要),以便结果字符串达到给定的长度。填充是从当前字符串的末尾(右侧)应用的。此交互式的源示例存储在 GitHub 存储库中。” source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…来源:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...

.substring - limits to the length you need .substring - 限制你需要的长度

If you choose to add ellipses, append them to the output.如果您选择添加省略号,请将它们附加到输出中。

I gave 4 examples of common JavaScript usages.我给出了 4 个常见的 JavaScript 用法示例。 I highly recommend using the String prototype with Overloading for legacy support.我强烈建议使用带有重载的 String 原型来获得遗留支持。 It makes it much easier to implement and change later.它使以后实施和更改变得更加容易。

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

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
    }

There are several ways to do achieve this有几种方法可以做到这一点

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);

}

You can also modify this function to get in between strings as well.您还可以修改此函数以进入字符串之间。

Prefer String.prototype.slice over the String.prototype.substring method (in substring , for some cases it gives a different result than what you expect).更喜欢String.prototype.slice而不是String.prototype.substring方法(在substring中,在某些情况下,它给出的结果与您期望的不同)。

Trim the string from LEFT to RIGHT:从左到右修剪字符串:

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)

Trim the string from RIGHT to LEFT: (-ve start index)从 RIGHT 到 LEFT 修剪字符串: (-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"

Here is my solution, which includes trimming white space too.这是我的解决方案,其中也包括修剪空白。

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) will return "Java.." trimToN('Javascript', 6, 2) 将返回“Java..”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM