Skip to content

Instantly share code, notes, and snippets.

@zaus
Last active August 4, 2022 11:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaus/64e9b1e547244e4a21a77a617b31f0cc to your computer and use it in GitHub Desktop.
Save zaus/64e9b1e547244e4a21a77a617b31f0cc to your computer and use it in GitHub Desktop.
Bookmarklet - Replace in Selected Text
  1. Copy the minified js content in this example
  2. Create a new bookmark
  3. In the "URL" field paste the copied text (ensuring it's prefixed with javascript:)
  4. Add bookmark to your favorite toolbar/folder
  5. Highlight some text on the page
  6. Click the bookmarklet and follow the prompts
(function() {
function getSelectionText() {
// https://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text
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 f = prompt("Find what? (regex)"),
r = prompt("Replace With?"),
i = getSelectionText(),
o = i.replace(new RegExp(f, 'gi'), r)
;
prompt("Copy the results", o);
})();
javascript:(function(){var e=prompt("Find what? (regex)"),t=prompt("Replace With?"),n=function(){var e="";return window.getSelection?e=window.getSelection().toString():document.selection&&"Control"!=document.selection.type&&(e=document.selection.createRange().text),e}().replace(new RegExp(e,"gi"),t);prompt("Copy the results",n)})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment