Search code examples
javascriptbookmarklet

Javascript edit text in selection via Bookmarklet


I am trying to make a simple bookmarklet (bookmark with javascript applet) that will get the selected text, reverse it, and then change it on screen. For example, if the user selects some text, say, the word hello, and then activates this bookmarklet, the text would then turn into olleh. So far I have the following:

javascript:
function getSelectedText() {
var text = "";
if (window.getSelection) {
    text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
}
    return text;
}
var selectedText = getSelectedText();
var textArray = selectedText.split("");
var reverseArray = textArray.reverse();
var reverseText = reverseArray.join("");
alert(reverseText);

I got the getSelectedText() function from here. At the end, the bookmarklet simply alerts the reversed text. How do you make it so that it actually replaces the text on the page? Thanks in advance for any possible help.


Solution

  • You can add this to the end:

    var nodeValue = window.getSelection().baseNode.nodeValue;
    window.getSelection().baseNode.nodeValue = nodeValue.replace(selectedText, reverseText);
    

    EDIT

    Use selection offset for reversing in the right place, str.replace only replaces the first occurrence of the word, and it can be wrong for common words such as "the".

    var selection = window.getSelection();
    var start = selection.anchorOffset;
    var end = selection.focusOffset;
    var nodeValue = selection.baseNode.nodeValue;
    var newValue = nodeValue.slice(0, start) + reverseText + nodeValue.slice(end);
    window.getSelection().baseNode.nodeValue = newValue;