How can I javascript truncate string without worrying about word boundaries?

I’m working with a dynamically loaded URL string that doesn’t have spaces, and I simply want to truncate it by character length. Here’s what I have so far:

var pathname = document.referrer; // won't work for file:// paths
document.getElementById("foo").innerHTML = "<a href='" + pathname + "'>" + pathname + "</a>";

What’s the best way to truncate this string in JavaScript?

I guess you may have heard about the slice() method — using this, we can extract a portion of a string based on the index positions provided.

Now, if you want to keep the first N characters and truncate the rest, you can use this approach and let your worries about boundaries be tossed away:

javascript

CopyEdit

var pathname = document.referrer;
var truncatedPathname = pathname.slice(0, 20); // Truncate to 20 characters
document.getElementById("foo").innerHTML = "<a href='" + pathname + "'>" + truncatedPathname + "</a>";

Simple, clean, and gets the job done!

Don’t worry mate I have got you covered. The substring() method extracts characters from the string, but it uses two arguments: the start index and the end index (not inclusive).

var pathname = document.referrer;
var truncatedPathname = pathname.substring(0, 20); // Truncate to 20 characters
document.getElementById("foo").innerHTML = "<a href='" + pathname + "'>" + truncatedPathname + "</a>";

I hope you like it.

I see @emma-crepeau and @joe-elmoufak have already given solid solutions to your problem — and yes, they’re correct. But there’s one more way to do this, and personally, I feel more comfortable with it.

This is done using TextContent and innerHTML with Custom Truncation.

If you’re working with dynamic content, especially when you might want to visually display truncated text (without necessarily altering the original string), you can manipulate the DOM directly by truncating the text and appending an ellipsis:

javascript

CopyEdit

var pathname = document.referrer;
var truncatedPathname = pathname.length > 20 ? pathname.substring(0, 20) + '...' : pathname;
document.getElementById("foo").innerHTML = "<a href='" + pathname + "'>" + truncatedPathname + "</a>";

How does it work? The code first checks whether the length of the string exceeds the truncation limit (in this case, 20 characters). If it does, it truncates the string to 20 characters and appends '...' to indicate it’s been shortened. If the string is shorter than or equal to 20 characters, it leaves it as is.

Why should you use this? Its flexibility is the answer — it dynamically adjusts based on the string length and ensures the truncation remains visually meaningful for users, especially handy when working with URLs or long dynamic text strings.

Well, thank me later :smile:.