alphahasher_obsidian-remove.../removeHyperlinks.ts
Clare Macrae ca69e9c411
Jest tests & plugin use same removeHyperlinks() (#3)
* Add 'ts-jest' dependency - preparing to convert test to TypeScript

* Add minimal jest.config.js

This tells Jest "when you see a .ts file, use ts-jest to transform it"

* Convert Jest test file from JavaScript to TypeScript

* Extract removeHyperlinks() to its own file, so it can be tested

Pure refactoring - done with the Move facility in WebStorm.

* Make tests check the removeHyperlinks() that is used by main.ts

Jest test now imports removeHyperlinks() used by main.ts,
removing the original need to keep the two copies of
removeHyperlinks() in sync.
2025-07-01 10:19:17 -07:00

33 lines
787 B
TypeScript

export function removeHyperlinks(text:string): string {
let result = text;
let match;
const regex = /\[((?:[^\]\\]|\\.|\](?!\())*?)\]\(/g;
while ((match = regex.exec(text)) !== null) {
const linkText = match[1];
const startPos = match.index;
const urlStartPos = match.index + match[0].length;
// Find the matching closing parenthesis
let parenCount = 1;
let urlEndPos = urlStartPos;
while (urlEndPos < text.length && parenCount > 0) {
if (text[urlEndPos] === '(') {
parenCount++;
} else if (text[urlEndPos] === ')') {
parenCount--;
}
if (parenCount > 0) {
urlEndPos++;
}
}
if (parenCount === 0) {
const fullMatch = text.substring(startPos, urlEndPos + 1);
result = result.replace(fullMatch, linkText);
}
}
return result;
}