225

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

Lucio
  • 3,428
  • 3
  • 37
  • 67
  • 3
    "this is" = 7 characters, did you intend that ? – aziz punjani Sep 18 '11 at 18:57
  • As said in the question, I'm not too sure how to use substring to do this. Could you please give me an example? I'll accept is an answer of course, if it works ;) @Interstellar_Coder oops, typo! –  Sep 18 '11 at 18:58

9 Answers9

448

Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
Frazer Kirkman
  • 716
  • 1
  • 10
  • 17
Will
  • 17,297
  • 7
  • 45
  • 48
  • Thanks! Works perfectly. I'll mark it as answer as soon as the time limit is passed! –  Sep 18 '11 at 19:01
  • 30
    And if you want ellipses for strings exceeding the max length (probably more helpful for longer max): var string = "this is a string"; var length = 20; var trimmedString = string.length > length ? string.substring(0, length - 3) + "..." : string.substring(0, length); – Will Sep 13 '12 at 15:19
  • 5
    Please note that string.substr(start, length) behaves strange, it will return empty if length is more than the length of the string. string.substring(start, end) works as expected, i.e. it will return the string up to it's end if there are not enough characters for the given end! – centic Feb 11 '15 at 14:53
  • 1
    Use `string.substr`. It has no strange behavior, despite the previous comment – Gibolt Aug 12 '17 at 04:51
  • `.substring(from, to)` takes [**indices**](https://stackoverflow.com/questions/3745515/what-is-the-difference-between-substr-and-substring#comment32007929_3745521). .substr(from, length) does not, Also .substr() [used to](http://www.visibone.com/products/ebk8-9_850.jpg) have an inconsistency in IE when the first argument is negative. – Bob Stein Jun 13 '19 at 12:24
  • Thanks.it works! – Khaled Rakhisi Apr 20 '21 at 20:54
64

Copying Will's comment into an answer, because I found it useful:

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/ :)

Community
  • 1
  • 1
Jon Lauridsen
  • 2,112
  • 1
  • 23
  • 26
  • 2
    No point in using `string.substring(0, length)` in the else case, since the string is guaranteed to be <= 20 chars at that point, just use `string`. – Nick Sweeting May 17 '16 at 21:46
  • 1
    To squeeze an extra two characters in, use the ellipsis character `…` – Ollie Sep 25 '20 at 00:21
16

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)
Samplasion
  • 454
  • 3
  • 12
Zameer Ansari
  • 23,672
  • 19
  • 120
  • 191
8

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

From link:

string.substr(start[, length])
kendaleiv
  • 5,493
  • 3
  • 26
  • 37
3

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.

  • Hello! It's good to also include some explanation on what's going on with your code. Given how similar your solution is to the accepted answer, perhaps a little detail on what the `padEnd` is doing. – Mattie Jan 24 '19 at 00:44
  • My solution, is much cleaner and more standardized plus it shows multiple usages. 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: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd – Matthew Egan Jan 24 '19 at 00:51
  • 1
    I'm not disputing the quality of your answer. Just a suggestion on how to make it better. Your explanation is great - edit your answer and put it in there! – Mattie Jan 24 '19 at 00:53
  • 1
    Hi Matt, I like your answer. It is pitty that you are replying to a little bit different question. He originally asked about trimming a string, not a returning fixed string length. – Jakub Kriz Jun 23 '20 at 12:20
0
    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...
MD. ABU TALHA
  • 415
  • 4
  • 12
0

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
    }
Olfredos6
  • 397
  • 4
  • 15
0

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.

Mitesh vaghela
  • 437
  • 4
  • 5
-2

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 ...
Babak
  • 17
  • 2
  • 1
    I'm curious as to why you added this answer. The question already has an accepted answer and several other reasonable answers, all of which are simpler than this. Or was your ":-)" intended to make this a joke? – Scott Sauyet Jan 01 '20 at 23:23
  • Note that the accepted answer is also the highest-rated answer. I think you're trying to solve a different problem here. (And I had not noticed that when commenting earlier.) It's not that it's an unlikely problem, but in the end it's only slightly related to the question asked. Yours also has the strange effect that with the given input, your output string is `23` characters long, longer than the `17` default parameter plus the `4` characters in the suffix `" ..."`. That seems odd. – Scott Sauyet Mar 06 '20 at 20:28
  • I also think this could use a [simpler implementation](https://gist.github.com/CrossEye/005bc0c848593bd37860978fe258dd27). – Scott Sauyet Mar 06 '20 at 20:47