gpt4 book ai didi

angular - 手动清理字符串

转载 作者:太空狗 更新时间:2023-10-29 16:54:22 25 4
gpt4 key购买 nike

我有一个 textarea,用户可以在其中输入一些文本。文本不能是 JavaScript 或 HTML 等。我想手动清理数据并将其保存为字符串。

我不知道如何使用 DomSanitizationService 手动清理我的数据。

如果我在页面上执行 {{ textare_text }},那么数据就会被正确清理。

如何手动对我拥有的 string 执行此操作?

最佳答案

您可以按如下方式清理 HTML:

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);
}

}

Demo plunker here .


根据您的评论,您实际上想要转义而不是 sanitizer 。

为此,check this plunker, where we have both escaping and 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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
.replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}
}

HTML escaping function上面使用的转义字符与 angular code does 相同(不幸的是,他们的转义函数不是公开的,所以我们不能使用它)。

关于angular - 手动清理字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com