Skip to content

Commit

Permalink
get-attribute.js now supports single quotes
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielJDufour committed Apr 7, 2023
1 parent 689b525 commit 99616dd
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
16 changes: 10 additions & 6 deletions get-attribute.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ function getAttribute(tag, attributeName, options) {
// only search for attributes in the opening tag
const opening = xml.slice(0, xml.indexOf(">") + 1);

const pattern = `${attributeName}\\="\([^"]*\)"`;
if (debug) console.log("[xml-utils] pattern:", pattern);
const quotechars = ['"', "'"];
for (let i = 0; i < quotechars.length; i++) {
const char = quotechars[i];
const pattern = attributeName + "\\=" + char + "([^" + char + "]*)" + char;
if (debug) console.log("[xml-utils] pattern:", pattern);

const re = new RegExp(pattern);
const match = re.exec(opening);
if (debug) console.log("[xml-utils] match:", match);
if (match) return match[1];
const re = new RegExp(pattern);
const match = re.exec(opening);
if (debug) console.log("[xml-utils] match:", match);
if (match) return match[1];
}
}

module.exports = getAttribute;
Expand Down
4 changes: 4 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,3 +195,7 @@ test("should handle nested tags", ({ eq }) => {
]);
eq(findTagByPath(xml, ["Thing"]).outer, xml);
});

test("getAttribute with single quotes", ({ eq }) => {
eq(getAttribute("<link href='https://example.org'/>", "href"), "https://example.org");
});

0 comments on commit 99616dd

Please sign in to comment.