@Paul – I'm not too much into AppleScript, but you are using the "contents" (unformatted text) property of an object.
How would it work if you are using the text directly?
Dummycode here (don't know if it will work at all):
set myText to text of selection of myDocument
in JavaScript (ExtendScript) that would be:
var myText = app.selection[0].texts[0];
What exactly is selected? A text frame? Or is it the text itself?
Uwe