it-tools/src/tools/url-text-fragment-maker/url-text-fragment-maker.service.ts
sharevb b779beb695 feat(new tool): URL Text Fragment Generator
Allows to generate an URL that make highlight in web pages (see https://developer.mozilla.org/en-US/docs/Web/Text_fragments)
2024-03-03 09:57:21 +01:00

36 lines
1.2 KiB
TypeScript

export function getUrlWithTextFragment(
{ url, textStartSearch, textStopSearch, prefixSearch, suffixSearch }:
{ url: string
textStartSearch: string
textStopSearch?: string
prefixSearch?: string
suffixSearch?: string
},
) {
const isValidUrl = (urlString: string) => {
try {
return Boolean(new URL(urlString));
}
catch (e) {
return false;
}
};
if (!isValidUrl(url)) {
throw new Error('Invalid url');
}
if (!url.match(/^https?:\/\//)) {
throw new Error('Url must have http:// or https:// prefix');
}
const [textStartSearchFirstText, ...textStartSearchOtherTexts] = textStartSearch.split(',');
const text = `${encodeURIComponent(prefixSearch ?? '')}-,${encodeURIComponent(textStartSearchFirstText.trim())},${encodeURIComponent(textStopSearch ?? '')},-${encodeURIComponent(suffixSearch ?? '')}`
.replace(/^-,|,(?=,)|,-$/g, '')
.replace(/,+/g, ',');
let textStartSearchOtherTextEncoded = textStartSearchOtherTexts.map(t => `text=${encodeURIComponent(t.trim())}`).join('&');
if (textStartSearchOtherTextEncoded.length) {
textStartSearchOtherTextEncoded = `&${textStartSearchOtherTextEncoded}`;
}
return `${url.trim()}#:~:text=${text}${textStartSearchOtherTextEncoded}`;
}