Skip to content

Commit

Permalink
capitalizeTitle(): Handle HTML tags
Browse files Browse the repository at this point in the history
  • Loading branch information
dstillman committed Apr 14, 2024
1 parent fbc4d6a commit eab0922
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
16 changes: 15 additions & 1 deletion test/tests/utilitiesTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,21 @@ describe("Zotero.Utilities", function() {
});
});
});


describe("#capitalizeTitle()", function () {
it("should capitalize within HTML tags", function () {
let input = 'Foo <b>bar</b> foo <em>bar</em>';
let expected = 'Foo <b>Bar</b> Foo <em>Bar</em>';
assert.equal(Zotero.Utilities.capitalizeTitle(input, true), expected);
});

it("shouldn't alter attributes within HTML tags", function () {
let input = 'Foo <span style="font-variant:small-caps;">bar</span> foo';
let expected = 'Foo <span style="font-variant:small-caps;">Bar</span> Foo';
assert.equal(Zotero.Utilities.capitalizeTitle(input, true), expected);
});
});

describe("walkNoteDOM()", function () {
it("should iterate subtrees in depth-first order and allow modifications", function () {
let html = loadTestData('note.html');
Expand Down
16 changes: 14 additions & 2 deletions utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -1042,9 +1042,16 @@ var Utilities = {
if (Zotero.Prefs && !Zotero.Prefs.get('capitalizeTitles') && !force) return string;
if (!string) return "";

// Remove HTML tags but remember their positions
let htmlTags = [];
let cleanedString = string.replace(/<[^>]+>/g, (match, offset) => {
htmlTags.push({ match, offset });
return "";
});

// split words
var words = string.split(delimiterRegexp);
var isUpperCase = string.toUpperCase() == string;
var words = cleanedString.split(delimiterRegexp);
var isUpperCase = cleanedString.toUpperCase() == cleanedString;

var newString = "";
var delimiterOffset = words[0].length;
Expand Down Expand Up @@ -1084,6 +1091,11 @@ var Utilities = {
newString += words[i];
}

// Reinsert HTML tags into their original positions
htmlTags.forEach(tag => {
newString = newString.substring(0, tag.offset) + tag.match + newString.substring(tag.offset);
});

return newString;
},

Expand Down

0 comments on commit eab0922

Please sign in to comment.