Search code examples
applescript

Parse URL with AppleScript


Given a url (https://www.stackoverflow.com/path-to-question), I am wondering if there is a way to parse the url to get its components in AppleScript/AppleScriptObjC directly (without using e.g. Javascript) and set them as variables; those components being:

  • protocol (i.e. https or http)
  • host (e.g. www.stackoverflow.com)
  • pathname (e.g. path-to-question)

I know one can do this via Javascript using

l = window.location
protocol = l.protocol
host = l.host
path = l.pathname

What I am trying to do: What I am trying to do is, given a current tab with URL (https://www.stackoverflow.com/path-to-question), change its URL to something like (https://(MY_TEXT1)-www.stackoverflow.com_(MY_TEXT2)/path-to-question_(MY_TEXT3))

Any help with how to do this via AppleScript directly would be much appreciated


Solution

  • With the help to the Foundation framework it's pretty easy

    set urlString to "https://www.stackoverflow.com/path-to-question"
    set urlComponents to my (NSURLComponents's componentsWithString: urlString)
    tell urlComponents
        set urlScheme to |scheme|() as text
        set urlHost to |host|() as text
        set urlPath to |path|() as text
    end tell
    

    If you need to omit the leading slash in the path just write

    set urlPath to text 2 thru -1 of (|path|() as text)