手动清理字符串 [英] Manually sanitize a string
问题描述
我有一个textarea
,用户将在其中键入一些文本.文本不能是JavaScript或HTML等.我想手动清理数据并将其保存为字符串.
I have an textarea
where the user will type in some text. The text cannot be JavaScript or HTML etc. I want to manually sanitize the data and save it to a string.
我不知道如何使用DomSanitizationService
手动清理数据.
I cannot figure out how to use DomSanitizationService
to manually sanitize my data.
如果在页面上执行{{ textare_text }}
,则数据已正确清除.
If I do {{ textare_text }}
on the page then the data is correctly sanitized.
我该如何手动操作我拥有的string
?
How do I do that manually to a string
I have?
推荐答案
您可以如下清理HTML:
You can sanitize the HTML as follows:
import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `
<div [innerHTML]="_htmlProperty"></div>
`
})
export class AppComponent {
_htmlProperty: string = 'AAA<input type="text" name="name">BBB';
constructor(private _sanitizer: DomSanitizer){ }
public get htmlProperty() : SafeHtml {
return this._sanitizer.sanitize(SecurityContext.HTML, this._htmlProperty);
}
}
根据您的评论,您实际上是想转义而不是消毒.
From your comments, you actually want escaping not sanitization.
为此,选中此朋克车,我们在其中进行了转义和消毒 .
import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `Original, using interpolation (double curly braces):<b>
<div>{{ _originalHtmlProperty }}</div>
</b><hr>Sanitized, used as innerHTML:<b>
<div [innerHTML]="sanitizedHtmlProperty"></div>
</b><hr>Escaped, used as innerHTML:<b>
<div [innerHTML]="escapedHtmlProperty"></div>
</b><hr>Escaped AND sanitized used as innerHTML:<b>
<div [innerHTML]="escapedAndSanitizedHtmlProperty"></div>
</b>`
})
export class AppComponent {
_originalHtmlProperty: string = 'AAA<input type="text" name="name">BBB';
constructor(private _sanitizer: DomSanitizer){ }
public get sanitizedHtmlProperty() : SafeHtml {
return this._sanitizer.sanitize(SecurityContext.HTML, this._originalHtmlProperty);
}
public get escapedHtmlProperty() : string {
return this.escapeHtml(this._originalHtmlProperty);
}
public get escapedAndSanitizedHtmlProperty() : string {
return this._sanitizer.sanitize(SecurityContext.HTML, this.escapeHtml(this._originalHtmlProperty));
}
escapeHtml(unsafe) {
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
.replace(/"/g, """).replace(/'/g, "'");
}
}
上面使用的 HTML转义功能与
The HTML escaping function used above escapes the same chars as angular code does (unfortunately, their escaping function is not public, so we can't use it).
这篇关于手动清理字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!