[javascript] Truncate a string straight JavaScript

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

This question is related to javascript truncate

The answer is


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

in case you want to truncate by word.

_x000D_
_x000D_
function limit(str, limit, end) {_x000D_
_x000D_
      limit = (limit)? limit : 100;_x000D_
      end = (end)? end : '...';_x000D_
      str = str.split(' ');_x000D_
      _x000D_
      if (str.length > limit) {_x000D_
        var cutTolimit = str.slice(0, limit);_x000D_
        return cutTolimit.join(' ') + ' ' + end;_x000D_
      }_x000D_
_x000D_
      return str.join(' ');_x000D_
    }_x000D_
_x000D_
    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);_x000D_
_x000D_
    console.log(limit);
_x000D_
_x000D_
_x000D_


Updated ES6 version

const truncateString = (string, maxLength = 50) => {
  if (!string) return null;
  if (string.length <= maxLength) return string;
  return `${string.substring(0, maxLength)}...`;
};

truncateString('what up', 4); // returns 'what...'

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

yes, substring. You don't need to do a Math.min; substring with a longer index than the length of the string ends at the original length.

But!

document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"

This is a mistake. What if document.referrer had an apostrophe in? Or various other characters that have special meaning in HTML. In the worst case, attacker code in the referrer could inject JavaScript into your page, which is a XSS security hole.

Whilst it's possible to escape the characters in pathname manually to stop this happening, it's a bit of a pain. You're better off using DOM methods than fiddling with innerHTML strings.

if (document.referrer) {
    var trimmed= document.referrer.substring(0, 64);
    var link= document.createElement('a');
    link.href= document.referrer;
    link.appendChild(document.createTextNode(trimmed));
    document.getElementById('foo').appendChild(link);
}

Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.

function truncateOnWord(str, limit) {
        var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
        var reg = new RegExp('(?=[' + trimmable + '])');
        var words = str.split(reg);
        var count = 0;
        return words.filter(function(word) {
            count += word.length;
            return count <= limit;
        }).join('');
    }

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

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

_x000D_
_x000D_
var pa = document.getElementsByTagName('p')[0].innerHTML;_x000D_
var rpa = document.getElementsByTagName('p')[0];_x000D_
// console.log(pa.slice(0, 30));_x000D_
var newPa = pa.slice(0, 29).concat('...');_x000D_
rpa.textContent = newPa;_x000D_
console.log(newPa)
_x000D_
<p>_x000D_
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_x000D_
</p>
_x000D_
_x000D_
_x000D_