Search code examples
javascriptstringtrimstrip

Why is the trim() method not working but instead breaking my function?


I don't understand why the trim() method isn't working for me here:

function addLink() {
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
    selection = selection.trim(); // *** HERE IT IS! ***
    var pagelink = "<br /><br /> Read more at: <a href='"+document.location.href+"'>"+document.location.href+"</a><br />Copyright &copy; Name";
    var copytext = "&ldquo;" + selection + "&rdquo;" + pagelink;
    var newdiv = document.createElement('div');
    newdiv.style.position='absolute';
    newdiv.style.left='-99999px';
    body_element.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);
    window.setTimeout(function() {
        body_element.removeChild(newdiv);
    },0);
}
document.oncopy = addLink;

It's not only that it doesn't do what it's supposed to, but it seems there's an error in my use of the method here, as it breaks the function.

I got this copy-attribution javascript function off the web. It works perfectly per se, but I need to add double quotes at the beginning and end of the copied selection, so I need to add a trim() method to avoid copied sentences such as:

" Hello, I have an empty space at the beginning!"

I've tried putting the trim() method everywhere but whatever I do, it breaks the function completely. I've read and reread the method's explanation and I don't see what I'm doing wrong... I mean, it should be pretty straightforward: you grab a string, add the trim() method to it, and that'll create a new string without any leading or trailing white spaces... But it seems I must be missing something here, as it simply breaks the function... Javascript and me have never been able to become good friends, to be honest; I've always found it frustrating, and rather convoluted, as a pose to, say, PHP, which doesn't mind being placed one way or another! (Of course, I'm talking of how it seems to my brain! I'm sure all of you pros here have it perfectly down and know where things go and why—and why they don't work the way I'm using them!)

Anyway, I've also tried using the strip() method (though I can't understand what is the difference) and the result is the same: it breaks the function.

Thanks in advance for any input on this!


Solution

  • window.getSelection() doesn't return a string, it returns a Selection object. You need to convert it to a string in order to call string methods on it.

    selection = selection.toString().trim();