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
on changeCaseOfText(theText, theCaseToSwitchTo)if theCaseToSwitchTo contains "lower" thenset theComparisonCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"set theSourceCharacters to "abcdefghijklmnopqrstuvwxyz"else if theCaseToSwitchTo contains "upper" thenset theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"elsereturn theTextend ifset theAlteredText to ""repeat with aCharacter in theTextset theOffset to offset of aCharacter in theComparisonCharactersif theOffset is not 0 thenset theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as stringelseset theAlteredText to (theAlteredText & aCharacter) as stringend ifend repeatreturn theAlteredTextend changeCaseOfText
JAVASCRIPT
function changeCaseOfText(text, caseToSwitchTo) {var alteredText = textif (caseToSwitchTo === "lower") {alteredText = alteredText.toLowerCase()}else if (caseToSwitchTo === "upper") {alteredText = alteredText.toUpperCase()}return alteredText}
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
changeCaseOfText("scripting is awesome!", "upper")--> Result: "SCRIPTING IS AWESOME!"
JAVASCRIPT
changeCaseOfText("scripting is awesome!", "upper")// 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
changeCaseOfText("DOING REPETITIVE WORK IS BORING", "lower")--> Result: "doing repetitive work is boring"
JAVASCRIPT
changeCaseOfText("DOING REPETITIVE WORK IS BORING", "lower")// 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
on findAndReplaceInText(theText, theSearchString, theReplacementString)set AppleScript's text item delimiters to theSearchStringset theTextItems to every text item of theTextset AppleScript's text item delimiters to theReplacementStringset theText to theTextItems as stringset AppleScript's text item delimiters to ""return theTextend findAndReplaceInText
Listing 19-10 shows how to call the handler in Listing 19-9.
APPLESCRIPT
set theText to "On Tuesday, I told you to have the report ready by next Tuesday."set theText to findAndReplaceInText(theText, "Tuesday", "Friday")--> 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
var text = "On Tuesday, I told you to have the report ready by next Tuesday."text = text.replace("Tuesday", "Friday")// 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
var text = "On Tuesday, I told you to have the report ready by next Tuesday."text = text.replace(/Tuesday/g, "Friday")// 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
set theText to "The quick brown fox jumps over a lazy dog."characters of theText--> 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
var text = "The quick brown fox jumps over a lazy dog."text.split("")// 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
set theText to "The quick brown fox jumps over a lazy dog."length of theText--> Result: 42
JAVASCRIPT
var text = "The quick brown fox jumps over a lazy dog."text.length// 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
set theText to "* Sal* Ben* Chris* David"paragraphs of theText--> Result: {"* Sal", "* Ben", "* Chris", "* David"}
JAVASCRIPT
var text = `* Sal* Ben* Chris* David`text.split("\n")// 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
set theText to "The quick brown fox jumps over a lazy dog."offset of "quick" in theText--> 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
var text = "The quick brown fox jumps over a lazy dog."text.indexOf("quick")// Result: 4
Splitting Text
The handler in Listing 19-23 splits text into a list, based on a specific delimiter.
APPLESCRIPT
on splitText(theText, theDelimiter)set AppleScript's text item delimiters to theDelimiterset theTextItems to every text item of theTextset AppleScript's text item delimiters to ""return theTextItemsend splitText
Listing 19-24 shows how to call the handler in Listing 19-23.
APPLESCRIPT
set theText to "The quick brown fox jumps over a lazy dog."splitText(theText, space)--> 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
var text = "The quick brown fox jumps over a lazy dog."text.split(" ")// 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
on trimText(theText, theCharactersToTrim, theTrimDirection)set theTrimLength to length of theCharactersToTrimif theTrimDirection is in {"beginning", "both"} thenrepeat while theText begins with theCharactersToTrimtryset theText to characters (theTrimLength + 1) thru -1 of theText as stringon error-- text contains nothing but trim charactersreturn ""end tryend repeatend ifif theTrimDirection is in {"end", "both"} thenrepeat while theText ends with theCharactersToTrimtryset theText to characters 1 thru -(theTrimLength + 1) of theText as stringon error-- text contains nothing but trim charactersreturn ""end tryend repeatend ifreturn theTextend trimText
JAVASCRIPT
function trimText(text, charsToTrim, direction) {var result = textvar regexString = charsToTrim.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");if (direction === "beginning" || direction === "both") {var regex = new RegExp(`^(?:${regexString})*`)result = result.replace(regex, "")}if (direction === "end" || direction === "both") {var regex = new RegExp(`(?:${regexString})*$`)result = result.replace(regex, "")}return result}
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
trimText("----1----", "-", "beginning")--> Result: "1----"
JAVASCRIPT
trimText("----1----", "-", "beginning")// 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
trimText("12345.txt", ".txt", "end")--> Result: "12345"
JAVASCRIPT
trimText("12345.txt", ".txt", "end")// 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
trimText("*-*-Ben*-*-", "*-", "both")--> Result: "Ben"
JAVASCRIPT
trimText("*-*-Ben*-*-", "*-", "both")// Result: "Ben"
Trimming Paragraphs of Text
The handlers in Listing 19-36 and Listing 19-37 remove unwanted characters from multiple paragraphs.
APPLESCRIPT
on trimParagraphsOfText(theText, theCharactersToTrim, theTrimDirection)set theParagraphs to every paragraph of theTextrepeat with a from 1 to count of paragraphs of theTextset theCurrentParagraph to item a of theParagraphsset item a of theParagraphs to trimText(theCurrentParagraph, theCharactersToTrim, theTrimDirection)end repeatset AppleScript's text item delimiters to returnset theText to theParagraphs as stringset AppleScript's text item delimiters to ""return theTextend trimParagraphsOfText
JAVASCRIPT
function trimParagraphsOfText(text, charsToTrim, direction) {var paragraphs = text.split("\n")for (var i = 0; i < paragraphs.length; i++) {var currentParagraph = paragraphs[i]paragraphs[i] = trimText(currentParagraph, charsToTrim, direction)}return paragraphs.join("\n")}
Listing 19-38 and Listing 19-39 show how to call the handlers in Listing 19-36 and Listing 19-37.
APPLESCRIPT
set theText to "* Sal* Ben* Chris* David"trimParagraphsOfText(theText, "* ", "beginning")--> Result:(*"SalBenChrisDavid"*)
JAVASCRIPT
var text = `* Sal* Ben* Chris* David`trimParagraphsOfText(text, "* ", "beginning")// Result: "Sal\nBen\nChris\nDavid"
Copyright © 2018 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2016-06-13
