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 additions
use framework "Foundation"
property NSString : a reference to current application's NSString
Here’s the code for the handler:
on remove:remove_string fromString:source_string
set s_String to NSString's stringWithString:source_string
set r_String to NSString's stringWithString:remove_string
return s_String's stringByReplacingOccurrencesOfString:r_String withString:""
end remove:fromString:
Enjoy! 🙂
Posted on September 6, 2016, in 10.11, AppleScript and tagged applescript, html, markdown. Bookmark the permalink. Comments Off on applescript: remove characters from a string.