diff --git a/lib/__fixtures__/curriculum-helpers-html.ts b/lib/__fixtures__/curriculum-helpers-html.ts index 8981cf40..30f91bb2 100644 --- a/lib/__fixtures__/curriculum-helpers-html.ts +++ b/lib/__fixtures__/curriculum-helpers-html.ts @@ -22,9 +22,25 @@ not a comment not a comment `; +const htmlExampleHead = ` + + + + Piano + +`; + +const htmlInnerExample = ` + + Piano + +`; + const testValues = { htmlFullExample, htmlCodeWithCommentsRemoved, + htmlExampleHead, + htmlInnerExample, }; export default testValues; diff --git a/lib/__tests__/curriculum-helper.test.tsx b/lib/__tests__/curriculum-helper.test.tsx index 557d3413..d71cdb5d 100644 --- a/lib/__tests__/curriculum-helper.test.tsx +++ b/lib/__tests__/curriculum-helper.test.tsx @@ -12,7 +12,12 @@ const { stringWithWhiteSpaceChars, stringWithWhiteSpaceCharsRemoved } = const { cssFullExample, cssCodeWithCommentsRemoved } = cssTestValues; -const { htmlFullExample, htmlCodeWithCommentsRemoved } = htmlTestValues; +const { + htmlFullExample, + htmlCodeWithCommentsRemoved, + htmlExampleHead, + htmlInnerExample, +} = htmlTestValues; const { jsCodeWithSingleAndMultLineComments, @@ -170,6 +175,16 @@ describe("removeHtmlComments", () => { }); }); +describe("extractHTMLElement", () => { + const { extractHTMLElement } = helper; + it("returns null if no head is found", () => { + expect(typeof extractHTMLElement("", "head")).toBe(null); + }); + it("returns inner HTML string if a head is present", () => { + expect(extractHTMLElement(htmlExampleHead, "head")).toBe(htmlInnerExample); + }); +}); + describe("isCalledWithNoArgs", () => { const { isCalledWithNoArgs } = helper; it("returns a boolean", () => { diff --git a/lib/index.ts b/lib/index.ts index 95f96b40..5c844d9b 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -47,6 +47,19 @@ export function removeHtmlComments(str: string): string { return str.replace(/|$)/g, ""); } +/** + * Extracts the inner html of every element inside of an element + * @param {String} code a HTML string of the element to analyze + * @param {String} tag the name of the element to match. + * @returns {string | null} the inner html of every element inside the chosen element or `null` if there is no match. + */ +export function extractHTMLElement(code: string, tag): string | null { + const expression = new RegExp( + "(?<=<" + tag + "[^>]*>)(?:.|\\s*)*?(?=<\\/" + tag + "\\s*>)" + ); + return code.match(expression)?.toString() ?? null; +} + /** * Removes every CSS-comment from the string that is provided * @param {String} str a CSS-string where the comments need to be removed of