在Angular中,可以使用DomSanitizer
服务来比较来自HTML文件的两个字符串。
首先,确保在组件中注入DomSanitizer
服务:
import { DomSanitizer } from '@angular/platform-browser';
@Component({
// ...
})
export class YourComponent {
constructor(private sanitizer: DomSanitizer) { }
}
然后,使用bypassSecurityTrustHtml
方法将HTML字符串转换为安全的HTML:
sanitizeHtml(html: string) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
接下来,你可以在组件中使用sanitizeHtml
方法来比较两个HTML字符串:
htmlString1: string = 'Hello
';
htmlString2: string = 'World
';
compareHtmlStrings() {
const sanitizedHtml1 = this.sanitizeHtml(this.htmlString1);
const sanitizedHtml2 = this.sanitizeHtml(this.htmlString2);
if (sanitizedHtml1 === sanitizedHtml2) {
console.log('The HTML strings are equal.');
} else {
console.log('The HTML strings are not equal.');
}
}
请注意,bypassSecurityTrustHtml
方法将HTML字符串标记为安全,以避免XSS攻击。因此,当比较两个HTML字符串时,需要确保它们都被正确地标记为安全的HTML。
希望这可以帮到你!
上一篇:比较来自返回函数的值