Truncate a string straight JavaScript

Viewed 408085

I'd like to truncate a dynamically loaded string using straight JavaScript. It's a url, so there are no spaces, and I obviously don't care about word boundaries, just characters.

Here's what I got:

var pathname = document.referrer; //wont work if accessing file:// paths
document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"
16 Answers

Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges:

function truncateString(str, num) {
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}

Updated ES6 version

const truncateString = (string = '', maxLength = 50) => 
  string.length > maxLength 
    ? `${string.substring(0, maxLength)}…`
    : string

// demo the above function
alert(truncateString('Hello World', 4));

Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.

From the documentation:

Truncates a string. Unless split is true, truncate will not split words up, and instead discard the word where the truncation occurred.

Example:

'just sittin on the dock of the bay'.truncate(20)

Output:

just sitting on...

Yes, substring works great:

stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"

var stringTruncate = function(str, length){
  var dots = str.length > length ? '...' : '';
  return str.substring(0, length)+dots;
};

One line ES6 Solution

Instead of just truncating the string, it also adds an ending string if the string length exceeds the given length.

const limit = (string, length, end = "...") => {
    return string.length < length ? string : string.substring(0, length) + end
}

limit('Hello world', 5) // Hello...

Besides the substring method, i found a nice little JS lib for this purpose.

It has mutliple useful methods in vanilla javascript to truncate a string.

Truncation by characters:

var pathname = 'this/is/thepathname';
document.getElementById("foo").innerHTML = "<a class='link' href='" + pathname +"'>" + pathname +"</a>"

// call the plugin - character truncation only needs a one line init
new Cuttr('.link', { length: 10 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>

<div id="foo"></div>

Simply add a class to the a and init the plugin.

Multiline text clipping is also possible.
More options like word oder sentences truncation are mentioned in the cuttr.js docs on the github page.

in case you want to truncate by word.

function limit(str, limit, end) {

      limit = (limit)? limit : 100;
      end = (end)? end : '...';
      str = str.split(' ');
      
      if (str.length > limit) {
        var cutTolimit = str.slice(0, limit);
        return cutTolimit.join(' ') + ' ' + end;
      }

      return str.join(' ');
    }

    var limit = limit('ILorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus magna, maximus a dictum et, hendrerit ac ligula. Vestibulum massa sapien, venenatis et massa vel, commodo elementum turpis. Nullam cursus, enim in semper luctus, odio turpis dictum lectus', 20);

    console.log(limit);

var str = "Anything you type in.";
str.substring(0, 5) + "" //you can type any amount of length you want

You can fix this method with the help of internal JavaScript methods

const truncate = (text, len) => {
  if (text.length > len && text.length > 0) {
    return `${text.split(" ").slice(0, len).join(" ")} ...`;
  } else {
    return text;
  }
};

var pa = document.getElementsByTagName('p')[0].innerHTML;
var rpa = document.getElementsByTagName('p')[0];
// console.log(pa.slice(0, 30));
var newPa = pa.slice(0, 29).concat('...');
rpa.textContent = newPa;
console.log(newPa)
<p>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here
</p>

In case you want to truncate by Limit (symbols), but you don't want to cut the words (leave the last word intact) for not LONG text (head of post for example):

trancWord(str, limit) {
    str = str.split(' ');
    let summ = 0
    for (let [index, value]  of str.entries()) {
        summ  += value.length
        if (summ > limit) {
            let cutTolimit = str.slice(0, index);
            return str.slice(0, index).join(' ') + ' ' + '...';
        }
    }
    return str.join(' ');
}

For long String (some long Text of Post - Vue-3 use as Filter):

trancWord  (str, max){
        if (str.length <= max) { return str; }
        let subString = str.substr(0, max);
        return (str ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '...';
}

For truncating a String to a specific length, use the following one-linear arrow function in JavaScript:

const truncate = (str, len) => str.slice?.(0, len);
    
console.log(truncate("Hello, World!", 5));
// Expected Output: Hello

The above function uses the String.prototype.slice method, which takes a chunk of a string and returns it as a new string without changing the original.

The logic will be as follows

  • get the length of the string

  • if it is more than a threshold, get the substring and end with ellipsis or other notation

  • else, return the input string

    function truncateString(str: string, num: number, ending: string = '...') {
    return str.length > num ? str.slice(0, num) + ending : str; }

Related