Skip to main content

How to parse URLs in JXA

Whenever I want to do AppleScript-like automation which involves string manipulation, I reach for JXA instead.

If I want to parse URLs, I normally use the URL() constructor:

var urlString = "";

var url = new URL(urlString);

But if you try that in JXA, you get an error:

Error: ReferenceError: Can't find variable: URL

Instead, a way I’ve found to parse URLs in JXA is to use NSURL. It’s a slightly different interface to JavaScript’s standard URL class, but better than writing a URL parser from scratch:

var url = $.NSURL.URLWithString(urlString);

var scheme = ObjC.unwrap(url.scheme);
var host   = ObjC.unwrap(;
var path   = ObjC.unwrap(url.path);
var query  = ObjC.unwrap(url.query);

console.log("Scheme:", scheme);
console.log("Host:",   host);
console.log("Path:",   path);
console.log("Query:",  query);
/* Scheme: https */
/* Host: */
/* Path: /path/to/resource */
/* Query: param1=value1&param2=value2 */

Note that the returned attributes (url.scheme,, etc.) are all instances of NSString, so they need to be unwrapped to get regular JavaScript strings.