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" then
set theComparisonCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set theSourceCharacters to "abcdefghijklmnopqrstuvwxyz"
else if theCaseToSwitchTo contains "upper" then
set theComparisonCharacters to "abcdefghijklmnopqrstuvwxyz"
set theSourceCharacters to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
else
return theText
end if
set theAlteredText to ""
repeat with aCharacter in theText
set theOffset to offset of aCharacter in theComparisonCharacters
if theOffset is not 0 then
set theAlteredText to (theAlteredText & character theOffset of theSourceCharacters) as string
else
set theAlteredText to (theAlteredText & aCharacter) as string
end if
end repeat
return theAlteredText
end changeCaseOfText
JAVASCRIPT
function changeCaseOfText(text, caseToSwitchTo) {
var alteredText = text
if (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 theSearchString
set theTextItems to every text item of theText
set AppleScript's text item delimiters to theReplacementString
set theText to theTextItems as string
set AppleScript's text item delimiters to ""
return theText
end 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 theDelimiter
set theTextItems to every text item of theText
set AppleScript's text item delimiters to ""
return theTextItems
end 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 theCharactersToTrim
if theTrimDirection is in {"beginning", "both"} then
repeat while theText begins with theCharactersToTrim
try
set theText to characters (theTrimLength + 1) thru -1 of theText as string
on error
-- text contains nothing but trim characters
return ""
end try
end repeat
end if
if theTrimDirection is in {"end", "both"} then
repeat while theText ends with theCharactersToTrim
try
set theText to characters 1 thru -(theTrimLength + 1) of theText as string
on error
-- text contains nothing but trim characters
return ""
end try
end repeat
end if
return theText
end trimText
JAVASCRIPT
function trimText(text, charsToTrim, direction) {
var result = text
var 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 theText
repeat with a from 1 to count of paragraphs of theText
set theCurrentParagraph to item a of theParagraphs
set item a of theParagraphs to trimText(theCurrentParagraph, theCharactersToTrim, theTrimDirection)
end repeat
set AppleScript's text item delimiters to return
set theText to theParagraphs as string
set AppleScript's text item delimiters to ""
return theText
end 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:
(*
"Sal
Ben
Chris
David"
*)
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