Skip to content

Commit

Permalink
feat(strip-html-tags): add deleted param
Browse files Browse the repository at this point in the history
  • Loading branch information
fupengl committed Oct 19, 2022
1 parent 535039d commit 7045a07
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
32 changes: 32 additions & 0 deletions __tests__/strings/strip-html-tags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,37 @@ describe('strings', () => {
allowed: 'p',
}),
).toBe('<p>hello bob</p>');

const html = `<script type="text/javascript" src="//www.17track.net/externalcall.js"></script>
<script type="text/javascript">
function doTrack() {
var num = document.getElementById("YQNum").value;
if(num===""){
alert("Enter your number.");
return;
}
YQV5.trackSingle({
//必须,指定承载内容的容器ID。
YQ_ContainerId:"YQContainer",
//可选,指定查询结果高度,最大为800px,默认为560px。
YQ_Height:560,
//可选,指定运输商,默认为自动识别。
YQ_Fc:"0",
//可选,指定UI语言,默认根据浏览器自动识别。
YQ_Lang:"en",
//必须,指定要查询的单号。
YQ_Num:num
});
}
</script>`;

expect(stripHtmlTags(html, { deleted: ['script'] })).toBe('\n');

expect(
stripHtmlTags(
`<script type="text/javascript" src="//www.17track.net/externalcall.js"></script><span>hello bob</span>`,
{ deleted: ['script'] },
),
).toBe('hello bob');
});
});
25 changes: 22 additions & 3 deletions src/string/strip-html-tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@ type stripHtmlTagsOption = {
* Array of allowed tags
* @default []
*/
allowed?: string;
allowed?: string[] | string;
/**
* Array of blocked tags
* @default []
*/
blocked?: string;
blocked?: string[] | string;
/**
* Array of deleted tags
* @default []
*/
deleted?: string[] | string;
};

/**
Expand All @@ -29,10 +34,20 @@ function stripHtmlTags(str: string, options: stripHtmlTagsOption = {}): string {

const tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
const commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
const tagWithContent =
/<([a-z][a-z0-9]*)\b[^<]*(?:(?!<\/([a-z][a-z0-9]*)>)<[^<]*)*<\/([a-z][a-z0-9]*)>/gi;

const replaceWith = options.replaceWith || '';
const allowed = options.allowed;
const blocked = options.blocked;
const deleted = options.deleted;

const replaceContent = function ($0, $1) {
if (deleted!.includes($1.toLowerCase())) {
return '';
}
return $0;
};

const replaceTags = function ($0, $1) {
if (blocked) {
Expand All @@ -46,7 +61,11 @@ function stripHtmlTags(str: string, options: stripHtmlTagsOption = {}): string {
let after = String(str);
while (true) {
const before = after;
after = before.replace(commentsAndPhpTags, replaceWith).replace(tags, replaceTags);
after = before.replace(commentsAndPhpTags, replaceWith);
if (deleted?.length) {
after = after.replace(tagWithContent, replaceContent);
}
after = after.replace(tags, replaceTags);

if (before === after) {
return after;
Expand Down

0 comments on commit 7045a07

Please sign in to comment.