How to trim a string to N chars in Javascript?

前端 未结 8 1551
暗喜
暗喜 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 18:44

    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

    "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." source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    .substring - limits to the length you need

    If you choose to add ellipses, append them to the output.

    I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.

提交回复
热议问题