How Do I Find & Replace Specific Text?

I was wondering if anybody knows how to find and replace a segment of text that is housed in a specific identifying bracket. In other words, I am writing an iTunes script that appends some text in the comments field. I want the script to be able overwright just that segment of text if I ran the script on the same file again, so it needs to find and replace if the text is there. For example, if the comments contains:

→ House - Progressive - Vocal ←

I want to be able to only replace what is inbetween the specific arrows. Here is a segment of the code where this addition belongs.

if class of currentTrack is file track then
set comment of currentTrack to "->> " & tagTransfer & " <<-"
end if

The general approach is:
-Find the offset of the opening tag (“->> “)
-Find the offset of the closing tag (” <<-”)
-Replace the existing text with all the existing text up to the opening tag, then the replacement text string, then all the existing text from the closing tag to the end of the text.

The following code will work for a string of indeterminate length. Replace “->> " and " <<-” with whatever your actual arrows are, and change the number in the second line to reflect the change. It assumes a single instance of each tag in the source text, and that they’re in the right order.

set theComment to comment of currentTrack
set commentStart to characters 1 through ((offset of "->> " in theComment) + 3) of theComment as string
set commentEnd to characters (offset of " <<-" in theComment) through (count of theComment) of theComment as string
set comment of currentTrack to commentStart & tagTransfer & commentEnd

To get a substring, use ‘text i thru j of str’ - it’s much quicker and safer than breaking the string into a list of characters then coercing it back to a string. Also, the OP says the tagged text is not always present so you’ll need to allow for that too, e.g.:

set theComment to "--> House - Progressive - Vocal <--"
set tagTransfer to "blah-blah"
set {openTag, closeTag} to {"--> ", " <--"}
	set commentStart to (text 1 through ((offset of openTag in theComment) -1 + (openTag's length))) of theComment
	set commentEnd to text (offset of closeTag in theComment) through -1 of theComment
	set theComment to commentStart & tagTransfer & commentEnd
on error number -1728 -- tags not found
end try
return theComment