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>"
Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges:
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.
Yes,
substring
works great: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!
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.
Use the substring method:
So in your case:
Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.
From the documentation:
Example:
Output: