Trim CRLF End and Start of Line

Dear Experts,

How can the below code be enhanced to ALSO trim CR/LF at the end of and start of the string:

on trim(someText)
	repeat until someText does not start with " "
		set someText to text 2 thru -1 of someText
	end repeat
	
	repeat until someText does not end with " "
		set someText to text 1 thru -2 of someText
	end repeat
	
	return someText
end trim

Thank you.

Hi,

there are probably a few different solutions,
this one splits the text into paragraphs and returns the first non-empty paragraph

on trimNewLineCharacters(someText)
	set theParagraphs to paragraphs of someText
	repeat with aParagraph in theParagraphs
		if contents of aParagraph is not "" then return contents of aParagraph
	end repeat
	return someText
end trimNewLineCharacters

Edit: Sorry, I overlooked ALSO

try this, you can add more characters to the list


property whiteSpaceAndNewlineCharacterSet : {tab, linefeed, return, space, character id 133}


on trimWhiteSpaceAndNewlineCharacters(someText)
	repeat until first character of someText is not in whiteSpaceAndNewlineCharacterSet
		set someText to text 2 thru -1 of someText
	end repeat
	
	repeat until last character of someText is not in whiteSpaceAndNewlineCharacterSet
		set someText to text 1 thru -2 of someText
	end repeat
	
	return someText
end trimWhiteSpaceAndNewlineCharacters


Great, thanks it works :smiley:

Just to show you another solution

do shell script "/bin/echo -n " & quoted form of theString & " | awk '{gsub(/^[ \\\t\\\r\\\n]+|[ \\\t\\\r\\\n]+$/,\"\")};1'"