Public
Edited
Dec 7, 2022
Importers
Also listed in…
Observable Tools
Insert cell
Insert cell
getNotebookUrlWithParams({ q: "hello" })
Insert cell
function getNotebookUrlWithParams(params = {}) {
const url = getNotebookUrl();

return addParams(url, params);
}
Insert cell
getNotebookUrl()
Insert cell
function getNotebookUrl() {
return removeHash(document.baseURI);
}
Insert cell
function removeHash(urlString) {
let url = new URL(urlString);

return urlString.replace(url.hash, "");
}
Insert cell
function addParams(url, params = {}) {
const urlCopy = new URL(url);

let paramsCopy = Object.fromEntries(urlCopy.searchParams.entries());
paramsCopy = {
...paramsCopy,
...params
};

// Remove params with undefined
const entries = Object.entries(paramsCopy).filter(
([_, v]) => v !== undefined
);
paramsCopy = Object.fromEntries(entries);

const newParams = new URLSearchParams(Object.entries(paramsCopy)).toString();

const newUrl = new URL(
`${urlCopy.origin}${urlCopy.pathname}${
newParams.length ? "?" : ""
}${newParams}`
);
return newUrl.href;
}
Insert cell
addParams("https://example.com", {
number: 1,
string: "hello",
null: null,
undefined: undefined
})
Insert cell
addParams("https://example.com")
Insert cell
params = new URLSearchParams(location.search)
Insert cell
getObservableSlug(getNotebookUrl())
Insert cell
function getObservableSlug(url) {
const observableHostname = "observablehq.com";

// url might be invalid (e.g. plain text)
try {
const u = new URL(url);

if (u.hostname !== observableHostname) return;

const parts = u.pathname.split("/").filter((s) => s.length);

if (parts[0].startsWith("@")) {
// URLs like https://observablehq.com/@abc/a-notebook
return parts[0] + "/" + parts[1];
} else if (parts[0] === "d") {
// URLs like https://observablehq.com/d/09f6a0e652dc547a
return parts[1];
}
} catch (e) {
return;
}
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more