Tuesday, September 29, 2020

#1 2020-09-11 02:20:15 pm

wayland
Member
From:: Nha Trang
Registered: 2020-05-13
Posts: 55

return substring to the left of and including the delimiter

I have a string: "UNIT 1: LEISURE AND SPORT"

I want to extract the "UNIT 1:" part.

I was able to do that with the code below, but I'm wondering if there's a better or more elegant of way of doing it.


Applescript:


set unitName to "UNIT 1: LEISURE AND SPORT"
set reducedUnitNameList to characters 1 through (offset of ":" in unitName) of unitName
set reducedUnitName to reducedUnitNameList as string

Offline

 

#2 2020-09-11 02:39:03 pm

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 620

Re: return substring to the left of and including the delimiter

In this situation, the AppleScript Language Guide recommends the use of text rather than character to avoid the need to coerce a list to a string:

Applescript:

set unitName to "UNIT 1: LEISURE AND SPORT"
set reducedUnitName to text 1 through (offset of ":" in unitName) of unitName --> "UNIT 1:"

An alternative--as you are probably aware--is text item delimiters:

Applescript:

set unitName to "UNIT 1: LEISURE AND SPORT"
set text item delimiters to ":"
set reducedUnitName to text item 1 of unitName & ":" --> "UNIT 1:"
set text item delimiters to ""

In testing with Script Geek, the text-item-delimiter method is faster, although the difference is only one millisecond. FWIW, I would use the offset method.

Last edited by peavine (2020-09-11 05:15:37 pm)


2018 Mac mini - macOS Catalina

Offline

 

#3 2020-09-15 06:06:04 am

wayland
Member
From:: Nha Trang
Registered: 2020-05-13
Posts: 55

Re: return substring to the left of and including the delimiter

Thank you. Where do you download Script Geek? I tried to download it one time, but the link was dead.

Offline

 

#4 2020-09-15 06:54:06 am

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 620

Re: return substring to the left of and including the delimiter

You're welcome. Script Geek was recently moved to the Late Night Software site:

https://latenightsw.com/script-geek/

Last edited by peavine (2020-09-15 06:55:41 pm)


2018 Mac mini - macOS Catalina

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)