Find & Replace

iaian7 » blog   John Einselen, 16.02.11    

Though I rather like Safari’s find feature (command+f brings up the search bar, or command+g to find again without even opening the UI), there are countless times when I’ve needed a good find & replace function. Copying content into TextWrangler just to do basic text replacement is a huge hassle! Though a dedicated extension would be really nice, I figured a simple bookmarklet could do the trick. Sadly, after a few minutes of searching via Google, I didn’t find much; a few examples, but they attempted to modify all page elements, or were incomplete. I needed something more reliable for editing content only within the currently selected input or text field. So I wrote my own.

The following code should work in most modern browsers (though I’ve only tested it in Safari), and even escapes most regex special character to help prevent weird errors (solution via simonwillison.net).

javascript: var el=document.activeElement; if(el.value){ var findVal=prompt('Find this:',''); if(findVal){ var findRegex=new RegExp(findVal.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,'\\$&'),'gi'); var resultsNumber=el.value.match(findRegex); if(resultsNumber){ var replaceVal=prompt('Replace with:',''); if(replaceVal){ if(confirm('Are you sure you want to replace '+resultsNumber.length+' occurances of %22'+findVal+'%22 with %22'+replaceVal+'%22?'))el.value=el.value.replace(findRegex,replaceVal); } }else{alert('Sorry, no matches found for %22'+findVal+'%22');} } }else{alert('Sorry, no text field is selected');}

To use it yourself, just drag the following link into your bookmark bar (the script has been compressed for brevity’s sake).

Find & Replacebrowser bookmarklet

Keep in mind this is offered with no guarantees; you accept full responsibility, and I recommend saving your data first, just in case.

Make sure the desired text field is active, then click the bookmark to start the process. If it’s one of the first nine bookmarks, you can even use a keyboard shortcut to activate it by pressing command+[number key] (bookmarks are numbered starting with 1). The script will ask for the search term, the replacement term, and confirmation (along with the final number of terms being replaced). You can cancel at any point by simply pressing the escape key, and the script double checks the validity of the input at every step. For example, if you enter a search term that’s not present, the script will interrupt before you waste any time entering the desired replacement term. Nice!

There is one known limitation: it doesn’t work with text fields inside an iFrame. Without helper scripts embedded in the parent page, it can’t tell there’s a completely different HTML document it should be paying attention too.

bookmark