x number of chars from position y

Hello,

I’m trying to make myself a script that could delete text from item names, starting at position x (chosen by the user) to delete y number of chars.

Having a hard time, I don"t think what I’ve tried so far makes much sense.
I still have a problem with text item delimiters (I need those, right ?)…

Could anyone point me in the right direction please?

Best regards

Hi,

easiest way:


set theText to "abcdefghijklmnopqrstuvwxyz"
set thePosition to 7
set charactersToDelete to 4
tell theText to set newText to text 1 thru (thePosition - 1) & text (thePosition + charactersToDelete) thru -1
newText --> "abcdefklmnopqrstuvwxyz"

Its useful to know how to use them and they are very easy to use. Read the comments in the script below to understand each line of code.

set tid to AppleScript's text item delimiters

--This stores the current text item delimiter so that you can restore it later

set theText to "abcdefghijklmnopqrstuvwxyz"
set theoffset to offset of "g" in theText
--offset finds the position of first occurrence of "g". It is 7 in the above case

set thecharacters to text theoffset thru (theoffset + 3) in theText
--ghij

set AppleScript's text item delimiters to thecharacters
--the text items will be separated based on the occurrence of "ghij" because they are the new text item delimiters

set thenewText to text items of theText
--{"abcdef", "klmnopqrstuvwxyz"} is the result. As you see, "ghij" have been removed

set AppleScript's text item delimiters to ""
--we want to join the above two text items, so we assign the text item delimiters to blank

set thenewText to thenewText as text
--"abcdefklmnopqrstuvwxyz"

set AppleScript's text item delimiters to tid
--restoring the text item delimiters
thenewText

Thanks so much StefanK – it was easy indeed !

And Chris, this is much clearer to me now… I was able to rewrite the code you posted (well, in a slightly different way but it worked) by myself so your mission is accomplished :wink:

I really appreciate it, thanks :slight_smile: