Trim String

This routine will strip characters from the left, right, or both ends of a string. The characters to strip are passed along with the string to the handler. In the example, the character list to strip are white spaces but the list could be anything.

OS version: Any

property white_space : {space, tab, return, (ASCII character 10), (ASCII character 13)}

set the_string to " this is a string "
set the_string to (my trim_string(the_string, white_space, "both"))

on trim_string(the_string, trim_chars, trim_parameter)
	set start_char to 1
	set end_char to length of the_string
	set all_chars to (characters of the_string)
	
	if trim_parameter is in {"left", "both"} then
		repeat with each_char in all_chars
			if each_char is not in trim_chars then exit repeat
			set start_char to (start_char + 1)
		end repeat
	end if
	
	if trim_parameter is in {"right", "both"} then
		set all_chars to reverse of all_chars
		repeat with each_char in all_chars
			if each_char is not in trim_chars then exit repeat
			set end_char to (end_char - 1)
		end repeat
	end if
	
	try
		return text start_char thru end_char of the_string
	on error
		return ""
	end try
end trim_string

Hmm, I can’t seem to figure out how this works. I was hoping it would show me exactly what it does, but it looks like it just returns the value you entered in the first place. (" this is a string ") Or, it just removes a pre-defined number of characters from the end (or beginning) of your string.

I need to trim a string (of unknown length) down to the first 713 characters. The string has no spaces, and no useable delimiters; it looks like this only much longer:

Does your script currently solve my problem?

Since you know exactly what the parameters are every time, why not use something like this.



-- Obviously, theText needs to have more than 713 characters for this script to work
set theText to "000000000031111111111 11000000000021 1111111111100000000000211111111111"

set theChars to every character of theText
set finalResult to items 1 thru 713 of theChars as string

Perfect. Thanks!

Edit: erm, I should probably test it first, shouldn’t I? :stuck_out_tongue:
Stand by…

Yep. That works just fine. It took a little bit of tinkering, just because of the way my variable was set up, but all’s well that ends well.

Or, to avoid the intermediate every-character and 713-character lists:

-- Obviously, theText needs to have more than 713 characters for this script to work
set theText to "000000000031111111111 11000000000021 1111111111100000000000211111111111"

set finalResult to text 1 thru 713 of theText