word length

Sorry if this is a very basic question, I’m new to Applescript.

My question is:

I’ve set the name of a file to a variable. The problem is, the file name is too long. I need a way to delete the last four characters from the variable.

So I need a way to get the character count of the variable -4, and then set the variable to the new number.

Thanks for any help.

Hi,

this is quite easy


set a to "1234567890"
set b to text 1 thru -5 of a --> "123456"

Thanks,

What if the variable is set to a string of text? “Job_file” for example. How do I count the number of characters in the variable? Then delete the last the last 5 characters(_file). And then set the variable to “Job”?

Thanks for your help.

the minus sign before the 5 indicates offset from the right of the string. so characters 1 from the left thru 5 from the right no count.

exactly, text -1 is the rightmost character of the string.
You can count the string with

set len to count a

Your example

set a to "Job_file"
set b to text 1 thru -5 of a 
--> "Job_"

PS:

or if the length is not constant and the string can be splited always by the underline character


set a to "Job_file"
set b to text 1 thru ((offset of "_" in a) - 1) of a --> "Job"

Thanks

If you just want to truncate, you can do that too:

set a to "123456789012345678"
set b to text 1 thru -5 of a --> "12345678901234"
set c to length of a
set maxlength to 10
if c > maxlength then
	set d to text 1 thru maxlength of a
end if
display dialog a & return & b & return & c & return & d