views:

5469

answers:

2

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>"
+8  A: 

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>"
Larsenal
thanks so much! :)
Bobby
rut-roh, doesn't seem to be working in safari4!
Bobby
thanks for the update.
Bobby
+3  A: 

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);
}
bobince
i'm confused, how does your solution avoid the security hole?
Bobby
bobince
meant to say thanks for the tip ;)
Bobby