Skip to content

Commit

Permalink
fix(module:core): fix HTML entities highlight error (#4162)
Browse files Browse the repository at this point in the history
close #4152
  • Loading branch information
hsuanxyz authored and Wendell committed Sep 20, 2019
1 parent 50b86be commit 2665762
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
15 changes: 15 additions & 0 deletions components/core/highlight/highlight.pipe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,19 @@ describe('NzHighlightPipe', () => {
'<span>&lt;script&gt;alert(&#34;he</span>llo&#34;)&lt;/script&gt;'
);
});

it('should highlight HTML entities', () => {
expect(pipe.transform('abc<>&"¢¥~®™Abc', 'a', 'igm')).toEqual(
'<span>a</span>bc&lt;&gt;&amp;&#34;&#162;&#165;~&#174;&#8482;<span>A</span>bc'
);
expect(pipe.transform('<>&"¢¥~®™', '>', 'igm')).toEqual(
'&lt;<span>&gt;</span>&amp;&#34;&#162;&#165;~&#174;&#8482;'
);
expect(pipe.transform('&forall;&nabla;&#8364;&#x20AC;', '&', 'g')).toEqual(
'<span>&amp;</span>forall;<span>&amp;</span>nabla;<span>&amp;</span>#8364;<span>&amp;</span>#x20AC;'
);
expect(pipe.transform('e😀m😁o😂j🤣i', '😂j', 'g')).toEqual(
'e&#128512;m&#128513;o<span>&#128514;j</span>&#129315;i'
);
});
});
16 changes: 8 additions & 8 deletions components/core/highlight/highlight.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,18 @@ function encodeEntities(value: string): string {
pure: true
})
export class NzHighlightPipe implements PipeTransform {
transform(value: string, highlightValue: string, flags?: string, klass?: string): string | null {
// Make it to display HTML string
const encodedValue = encodeEntities(value);
private UNIQUE_WRAPPERS: [string, string] = ['##==-open_tag-==##', '##==-close_tag-==##'];

transform(value: string, highlightValue: string, flags?: string, klass?: string): string | null {
if (!highlightValue) {
return encodedValue;
return value;
}

const encodedHighlightValue = encodeEntities(highlightValue);

// Escapes regex keyword to interpret these characters literally
const searchValue = new RegExp(encodedHighlightValue.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$&'), flags);
return encodedValue.replace(searchValue, str => `<span${klass ? ` class="${klass}"` : ''}>${str}</span>`);
const searchValue = new RegExp(highlightValue.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$&'), flags);
const wrapValue = value.replace(searchValue, `${this.UNIQUE_WRAPPERS[0]}$&${this.UNIQUE_WRAPPERS[1]}`);
return encodeEntities(wrapValue)
.replace(new RegExp(this.UNIQUE_WRAPPERS[0], 'g'), klass ? `<span class="${klass}">` : '<span>')
.replace(new RegExp(this.UNIQUE_WRAPPERS[1], 'g'), '</span>');
}
}

0 comments on commit 2665762

Please sign in to comment.