javascripttruncate

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

Solution

  • Use the substring method:

    var length = 3;
    var myString = "ABCDEFG";
    var myTruncatedString = myString.substring(0,length);
    // The value of myTruncatedString is "ABC"
    

    So in your case:

    var length = 3;  // set to the number of characters you want to keep
    var pathname = document.referrer;
    var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length));
    
    document.getElementById("foo").innerHTML =
         "<a href='" + pathname +"'>" + trimmedPathname + "</a>"