Created
April 8, 2020 19:24
-
-
Save rolandcrosby/5f91572415a60aef428a35dc3beee35c to your computer and use it in GitHub Desktop.
rot13 the current selection in your browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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