@ciolabs/html-find-conditional-comments
Version:
Finds all conditional comments in a string
61 lines • 1.97 kB
JavaScript
// src/index.ts
var OPEN_REGEX = /<!(--)?\[if\s[\s\w!&()|]+]>(?:<!--+>)?/gi;
var CLOSE_REGEX = /(?:<!--)?<!\[endif](--) /gi;
function findConditionalComments(string_) {
const comments = [];
const stack = [];
let position = 0;
while (position < string_.length) {
OPEN_REGEX.lastIndex = position;
CLOSE_REGEX.lastIndex = position;
const openMatch = OPEN_REGEX.exec(string_);
const closeMatch = CLOSE_REGEX.exec(string_);
if (!openMatch && !closeMatch) {
break;
}
const nextOpenIndex = openMatch ? openMatch.index : Number.POSITIVE_INFINITY;
const nextCloseIndex = closeMatch ? closeMatch.index : Number.POSITIVE_INFINITY;
if (nextOpenIndex < nextCloseIndex && openMatch) {
const openText = openMatch[0];
const openStart = openMatch.index;
const openEnd = OPEN_REGEX.lastIndex;
const isComment = openText.startsWith("<!--");
const bubble = openText.endsWith("-->");
stack.push({
open: openText,
start: openStart,
end: openEnd,
isComment,
bubble
});
position = openEnd;
continue;
}
if (closeMatch) {
const closeText = closeMatch[0];
const closeEnd = CLOSE_REGEX.lastIndex;
if (stack.length > 0) {
const openState = stack.at(-1);
const closeHasDashes = Boolean(closeMatch[1]);
const openRequiresDashes = openState.isComment;
if (closeHasDashes === openRequiresDashes) {
stack.pop();
comments.push({
isComment: openState.isComment,
open: openState.open,
close: closeText,
bubble: openState.bubble,
downlevel: openState.bubble || !openState.isComment ? "revealed" : "hidden",
range: [openState.start, closeEnd]
});
}
}
position = closeEnd;
}
}
return comments;
}
export {
findConditionalComments as default
};
//# sourceMappingURL=index.mjs.map