How to trim a string to N chars in Javascript?

JavascriptStringTrim

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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)

Solution 4 - Javascript

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

Prefer String.prototype.slice over the String.prototype.substring method (in substring, for some cases it gives a different result than what you expect).

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)

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"

Solution 8 - Javascript

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
    }

Solution 9 - Javascript

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.

Solution 10 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser825286View Question on Stackoverflow
Solution 1 - JavascriptWillView Answer on Stackoverflow
Solution 2 - JavascriptJon LauridsenView Answer on Stackoverflow
Solution 3 - JavascriptxameeramirView Answer on Stackoverflow
Solution 4 - JavascriptkendaleivView Answer on Stackoverflow
Solution 5 - JavascriptMD. ABU TALHAView Answer on Stackoverflow
Solution 6 - JavascriptMatthew EganView Answer on Stackoverflow
Solution 7 - JavascriptSridharKrithaView Answer on Stackoverflow
Solution 8 - JavascriptOlfredos6View Answer on Stackoverflow
Solution 9 - JavascriptMitesh vaghelaView Answer on Stackoverflow
Solution 10 - JavascriptBabakView Answer on Stackoverflow