Blog Archives
applescript: remove characters from a string

One of the things I’m often finding myself doing is trying to remove characters from strings, particularly html codes and other markdown clutter. Rather than laboriously messing around with offsets and the like, we can make our lives simpler by making a quick handler that leverages Cocoa’s stringByReplacingOccurrencesOfString method.
For example, suppose you’ve got a sourceString containing something like this

We can strip all the tags out by calling our handler like this, once for the opening tags and again for the closing tags. Note how the variable names have changed in the second call:

The beauty of this is it doesn’t just remove one instance of the tag, it removes all occurrences of them, so this handler is a real life-saver when you’ve got a whole page of markdown to clean.
To achieve this you’ll need to add a couple of declarations to the top of your script, as well as the handler:
Here’s the declarations you’ll need:
use scripting additionsuse framework "Foundation"property NSString : a reference to current application's NSString
Here’s the code for the handler:
on remove:remove_string fromString:source_stringset s_String to NSString's stringWithString:source_stringset r_String to NSString's stringWithString:remove_stringreturn s_String's stringByReplacingOccurrencesOfString:r_String withString:""end remove:fromString:
Enjoy! 🙂
