Documentation Archive

Developer

Mac Automation Scripting Guide

On This Page

Manipulating Text

Manipulating text is one of the most common tasks performed in scripts. AppleScript and JavaScript both possess some basic text manipulation functions and properties that allow you to concatenate text, get the length of a string, and more. Overall, JavaScript has a much wider-range of built-in language-level text manipulation functions. Custom scripting is usually required to manipulate text with AppleScript.

Changing the Case of Text

The handlers in Listing 19-1 and Listing 19-2 convert text to uppercase or lowercase. To use these handlers, provide some source text and a case to apply—upper or lower.

APPLESCRIPT

Open in Script Editor

Listing 19-1AppleScript: Handler that converts text to uppercase or lowercase
  1. on changeCaseOfText(theText, theCaseToSwitchTo)
  2. if theCaseToSwitchTo contains "lower" then
  3. set theComparisonCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  4. set theSourceCharacters to "abcdefghijklmnopqrstuvwxyz"
  5. else if theCaseToSwitchTo contains "upper" then
  6. set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
  7. set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  8. else
  9. return theText
  10. end if
  11. set theAlteredText to ""
  12. repeat with aCharacter in theText
  13. set theOffset to offset of aCharacter in theComparisonCharacters
  14. if theOffset is not 0 then
  15. set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
  16. else
  17. set theAlteredText to (theAlteredText & aCharacter) as string
  18. end if
  19. end repeat
  20. return theAlteredText
  21. end changeCaseOfText

JAVASCRIPT

Open in Script Editor

Listing 19-2JavaScript: Function that converts text to uppercase or lowercase
  1. function changeCaseOfText(text, caseToSwitchTo) {
  2. var alteredText = text
  3. if (caseToSwitchTo === "lower") {
  4. alteredText = alteredText.toLowerCase()
  5. }
  6. else if (caseToSwitchTo === "upper") {
  7. alteredText = alteredText.toUpperCase()
  8. }
  9. return alteredText
  10. }

Listing 19-3 and Listing 19-4 show how to call the handlers in Listing 19-1 and Listing 19-2 to convert text to uppercase.

APPLESCRIPT

Open in Script Editor

Listing 19-3AppleScript: Calling a handler to convert text to uppercase
  1. changeCaseOfText("scripting is awesome!", "upper")
  2. --> Result: "SCRIPTING IS AWESOME!"

JAVASCRIPT

Open in Script Editor

Listing 19-4JavaScript: Calling a function to convert text to uppercase
  1. changeCaseOfText("scripting is awesome!", "upper")
  2. // Result: "SCRIPTING IS AWESOME!"

Listing 19-5 and Listing 19-6 show how to call the handlers in Listing 19-1 and Listing 19-2 to convert text to lowercase.

APPLESCRIPT

Open in Script Editor

Listing 19-5AppleScript: Calling a handler to convert text to lowercase
  1. changeCaseOfText("DOING REPETITIVE WORK IS BORING", "lower")
  2. --> Result: "doing repetitive work is boring"

JAVASCRIPT

Open in Script Editor

Listing 19-6JavaScript: Calling a function to convert text to lowercase
  1. changeCaseOfText("DOING REPETITIVE WORK IS BORING", "lower")
  2. // Result: "doing repetitive work is boring"

Finding and Replacing Text in a String

The handler in Listing 19-9 can be used to find and replace text in a string. To use it, provide some source text, a string to find, and a replacement string. This handler replaces any found instances of the specified search string.

APPLESCRIPT

Open in Script Editor

Listing 19-9AppleScript: Handler that finds and replaces text in a string
  1. on findAndReplaceInText(theText, theSearchString, theReplacementString)
  2. set AppleScript's text item delimiters to theSearchString
  3. set theTextItems to every text item of theText
  4. set AppleScript's text item delimiters to theReplacementString
  5. set theText to theTextItems as string
  6. set AppleScript's text item delimiters to ""
  7. return theText
  8. end findAndReplaceInText

Listing 19-10 shows how to call the handler in Listing 19-9.

APPLESCRIPT

Open in Script Editor

Listing 19-10AppleScript: Calling a handler to find and replace text in a string
  1. set theText to "On Tuesday, I told you to have the report ready by next Tuesday."
  2. set theText to findAndReplaceInText(theText, "Tuesday", "Friday")
  3. --> Result: "On Friday, I told you to have the report ready by next Friday."

In JavaScript, the String object’s replace() method is used to find and replace text in a string, as shown in Listing 19-11. Unlike the previous AppleScript example, this function replaces only the first occurrence of the found text.

JAVASCRIPT

Open in Script Editor

Listing 19-11JavaScript: Finding and replacing the first occurrence of text in a string
  1. var text = "On Tuesday, I told you to have the report ready by next Tuesday."
  2. text = text.replace("Tuesday", "Friday")
  3. // Result: "On Friday, I told you to have the report ready by next Tuesday."

The replace() method can be combined with a regular expression to replace every occurrence of the found text, as shown in Listing 19-12.

JAVASCRIPT

Open in Script Editor

Listing 19-12JavaScript: Finding and replacing every occurrence of text in a string
  1. var text = "On Tuesday, I told you to have the report ready by next Tuesday."
  2. text = text.replace(/Tuesday/g, "Friday")
  3. // Result: "On Friday, I told you to have the report ready by next Friday."

Getting the Characters of a String

Listing 19-15 and Listing 19-16 show how to get a list of characters in a string.

APPLESCRIPT

Open in Script Editor

Listing 19-15AppleScript: Get the characters of a string
  1. set theText to "The quick brown fox jumps over a lazy dog."
  2. characters of theText
  3. --> Result: {"T", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "j", "u", "m", "p", "s", " ", "o", "v", "e", "r", " ", "a", " ", "l", "a", "z", "y", " ", "d", "o", "g", "."}

JAVASCRIPT

Open in Script Editor

Listing 19-16JavaScript: Get the characters of a string
  1. var text = "The quick brown fox jumps over a lazy dog."
  2. text.split("")
  3. // Result: ["T", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "j", "u", "m", "p", "s", " ", "o", "v", "e", "r", " ", "a", " ", "l", "a", "z", "y", " ", "d", "o", "g", "."]

Getting the Length of String

Listing 19-17 and Listing 19-18 show how to get the length of—the number of characters in—a string.

APPLESCRIPT

Open in Script Editor

Listing 19-17AppleScript: Get the length of a string
  1. set theText to "The quick brown fox jumps over a lazy dog."
  2. length of theText
  3. --> Result: 42

JAVASCRIPT

Open in Script Editor

Listing 19-18JavaScript: Get the length of a string
  1. var text = "The quick brown fox jumps over a lazy dog."
  2. text.length
  3. // Result: 42

Getting the Paragraphs of a String

Listing 19-19 and Listing 19-20 show how to get a list of paragraphs in a string.

APPLESCRIPT

Open in Script Editor

Listing 19-19AppleScript: Get the characters of a string
  1. set theText to "* Sal
  2. * Ben
  3. * Chris
  4. * David"
  5. paragraphs of theText
  6. --> Result: {"* Sal", "* Ben", "* Chris", "* David"}

JAVASCRIPT

Open in Script Editor

Listing 19-20JavaScript: Get the characters of a string
  1. var text = `* Sal
  2. * Ben
  3. * Chris
  4. * David`
  5. text.split("\n")
  6. // Result: ["* Sal", "* Ben", "* Chris", "* David"]

Getting the Position of Text in a String

To determine the position of text within a string in AppleScript, request its offset, as shown in Listing 19-21. This provides the character number where the first instance of the text begins.

APPLESCRIPT

Open in Script Editor

Listing 19-21AppleScript: Get the position of text in a string
  1. set theText to "The quick brown fox jumps over a lazy dog."
  2. offset of "quick" in theText
  3. --> Result: 5

To determine the position of text within a string in JavaScript, call the indexOf() method of the text object, as shown in Listing 19-22.

JAVASCRIPT

Open in Script Editor

Listing 19-22JavaScript: Get the position of text in a string
  1. var text = "The quick brown fox jumps over a lazy dog."
  2. text.indexOf("quick")
  3. // Result: 4

Splitting Text

The handler in Listing 19-23 splits text into a list, based on a specific delimiter.

APPLESCRIPT

Open in Script Editor

Listing 19-23AppleScript: Handler that splits text
  1. on splitText(theText, theDelimiter)
  2. set AppleScript's text item delimiters to theDelimiter
  3. set theTextItems to every text item of theText
  4. set AppleScript's text item delimiters to ""
  5. return theTextItems
  6. end splitText

Listing 19-24 shows how to call the handler in Listing 19-23.

APPLESCRIPT

Open in Script Editor

Listing 19-24AppleScript: Calling a handler to split text based on a delimiter
  1. set theText to "The quick brown fox jumps over a lazy dog."
  2. splitText(theText, space)
  3. --> Result: {"The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."}

In JavaScript, the String object’s split() method is used to split text based on a delimiter, as shown in Listing 19-25.

JAVASCRIPT

Open in Script Editor

Listing 19-25JavaScript: Function that splits text
  1. var text = "The quick brown fox jumps over a lazy dog."
  2. text.split(" ")
  3. // Result: ["The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."]

Trimming Text

The handlers in Listing 19-26 and Listing 19-27 trim text from the beginning or end of a string. To use these examples, provide some source text, characters to trim, and a trim direction—beginning (trim from the beginning), end (trim from the end), or both (trim from both the beginning and end).

APPLESCRIPT

Open in Script Editor

Listing 19-26AppleScript: Handler that trims text
  1. on trimText(theText, theCharactersToTrim, theTrimDirection)
  2. set theTrimLength to length of theCharactersToTrim
  3. if theTrimDirection is in {"beginning", "both"} then
  4. repeat while theText begins with theCharactersToTrim
  5. try
  6. set theText to characters (theTrimLength + 1) thru -1 of theText as string
  7. on error
  8. -- text contains nothing but trim characters
  9. return ""
  10. end try
  11. end repeat
  12. end if
  13. if theTrimDirection is in {"end", "both"} then
  14. repeat while theText ends with theCharactersToTrim
  15. try
  16. set theText to characters 1 thru -(theTrimLength + 1) of theText as string
  17. on error
  18. -- text contains nothing but trim characters
  19. return ""
  20. end try
  21. end repeat
  22. end if
  23. return theText
  24. end trimText

JAVASCRIPT

Open in Script Editor

Listing 19-27JavaScript: Function that trims text
  1. function trimText(text, charsToTrim, direction) {
  2. var result = text
  3. var regexString = charsToTrim.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  4. if (direction === "beginning" || direction === "both") {
  5. var regex = new RegExp(`^(?:${regexString})*`)
  6. result = result.replace(regex, "")
  7. }
  8. if (direction === "end" || direction === "both") {
  9. var regex = new RegExp(`(?:${regexString})*$`)
  10. result = result.replace(regex, "")
  11. }
  12. return result
  13. }

Listing 19-28 and Listing 19-29 show how to call the handlers in Listing 19-26 and Listing 19-27 to trim text from the beginning of a string.

APPLESCRIPT

Open in Script Editor

Listing 19-28AppleScript: Calling a handler to trim text from the beginning of a string
  1. trimText("----1----", "-", "beginning")
  2. --> Result: "1----"

JAVASCRIPT

Open in Script Editor

Listing 19-29JavaScript: Calling a function to trim text from the beginning of a string
  1. trimText("----1----", "-", "beginning")
  2. // Result: "1----"

Listing 19-30 and Listing 19-31 show how to call the handlers in Listing 19-26 and Listing 19-27 to trim text from the end of a string.

APPLESCRIPT

Open in Script Editor

Listing 19-30AppleScript: Calling a handler to trim text from the end of a string
  1. trimText("12345.txt", ".txt", "end")
  2. --> Result: "12345"

JAVASCRIPT

Open in Script Editor

Listing 19-31JavaScript: Calling a function to trim text from the end of a string
  1. trimText("12345.txt", ".txt", "end")
  2. // Result: "12345"

Listing 19-32 and Listing 19-33 show how to call the handlers in Listing 19-26 and Listing 19-27 to trim text from the beginning and end of a string.

APPLESCRIPT

Open in Script Editor

Listing 19-32AppleScript: Calling a handler to trim text from the beginning and end of a string
  1. trimText("*-*-Ben*-*-", "*-", "both")
  2. --> Result: "Ben"

JAVASCRIPT

Open in Script Editor

Listing 19-33JavaScript: Calling a function to trim text from the beginning and end of a string
  1. trimText("*-*-Ben*-*-", "*-", "both")
  2. // Result: "Ben"

Trimming Paragraphs of Text

The handlers in Listing 19-36 and Listing 19-37 remove unwanted characters from multiple paragraphs.

APPLESCRIPT

Open in Script Editor

Listing 19-36AppleScript: Handler that trims text on multiple paragraphs
  1. on trimParagraphsOfText(theText, theCharactersToTrim, theTrimDirection)
  2. set theParagraphs to every paragraph of theText
  3. repeat with a from 1 to count of paragraphs of theText
  4. set theCurrentParagraph to item a of theParagraphs
  5. set item a of theParagraphs to trimText(theCurrentParagraph, theCharactersToTrim, theTrimDirection)
  6. end repeat
  7. set AppleScript's text item delimiters to return
  8. set theText to theParagraphs as string
  9. set AppleScript's text item delimiters to ""
  10. return theText
  11. end trimParagraphsOfText

JAVASCRIPT

Open in Script Editor

Listing 19-37JavaScript: Function that trims text on multiple paragraphs
  1. function trimParagraphsOfText(text, charsToTrim, direction) {
  2. var paragraphs = text.split("\n")
  3. for (var i = 0; i < paragraphs.length; i++) {
  4. var currentParagraph = paragraphs[i]
  5. paragraphs[i] = trimText(currentParagraph, charsToTrim, direction)
  6. }
  7. return paragraphs.join("\n")
  8. }

Listing 19-38 and Listing 19-39 show how to call the handlers in Listing 19-36 and Listing 19-37.

APPLESCRIPT

Open in Script Editor

Listing 19-38AppleScript: Calling a handler to trim text from multiple paragraphs
  1. set theText to "* Sal
  2. * Ben
  3. * Chris
  4. * David"
  5. trimParagraphsOfText(theText, "* ", "beginning")
  6. --> Result:
  7. (*
  8. "Sal
  9. Ben
  10. Chris
  11. David"
  12. *)

JAVASCRIPT

Open in Script Editor

Listing 19-39JavaScript: Calling a function to trim text from multiple paragraphs
  1. var text = `* Sal
  2. * Ben
  3. * Chris
  4. * David`
  5. trimParagraphsOfText(text, "* ", "beginning")
  6. // Result: "Sal\nBen\nChris\nDavid"