Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
rot13 the current selection in your browser
(function () {
function rot13(str) {
return str.replace(/([A-Ma-m])|([N-Zn-z])/g, function (m, p1, p2) {
return String.fromCharCode(m.charCodeAt(0) + (p1 ? 13 : -13));
});
}
if (document.getSelection().rangeCount == 0) {
return;
}
const range = window.getSelection().getRangeAt(0);
const iter = document.createNodeIterator(
range.commonAncestorContainer,
NodeFilter.SHOW_TEXT
);
let el = iter.nextNode();
let more = true;
while (more) {
if (
el.compareDocumentPosition(range.startContainer) &
Node.DOCUMENT_POSITION_FOLLOWING ||
el.textContent.trim() === ""
) {
el = iter.nextNode();
more = !!el;
continue;
}
if (
el.compareDocumentPosition(range.endContainer) &
Node.DOCUMENT_POSITION_PRECEDING
) {
break;
}
let replacementText;
if (el === range.startContainer && el === range.endContainer) {
replacementText =
el.textContent.substring(0, range.startOffset) +
rot13(el.textContent.substring(range.startOffset, range.endOffset))
+ el.textContent.substring(range.endOffset);
} else if (el === range.startContainer) {
replacementText =
el.textContent.substring(0, range.startOffset) +
rot13(el.textContent.substring(range.startOffset));
} else if (el === range.endContainer) {
replacementText =
rot13(el.textContent.substring(0, range.endOffset)) +
el.textContent.substring(range.endOffset);
} else {
replacementText = rot13(el.textContent);
}
let elToReplace = el;
el = iter.nextNode();
more = !!el;
elToReplace.replaceWith(document.createTextNode(replacementText));
}
window.getSelection().removeAllRanges();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.