简体   繁体   中英

Only allow certain tags in contenteditable div

I have a contenteditable div and using keyboard shortcuts like ctrl+i the user is able to format the text. And as they type the innerHTML changes reflecting the tags ie:

Hello&nbsp;<i>thanks for&nbsp;<br><br>for showing up<b>&nbsp;y'all b</b></i>

This is fine, and works well for my purposes. but the issue arises that when I go to print the html in a different div IF a user adds any other html tags, they could really mess up the application.

For instance, if they added a <script> tag or style etc.. How do I make it that the user is only allowed to add <i> , <br> , <b> , <s> , and &nbsp; without being able to add anything else?

Any ideas? Thank you

I think that you can use a regExpresion to avoid the "indeseables" tags. Some like

<textarea #data [(ngModel)]="value" (input)="replace(data)"></textarea>
<div [innerHtml]="valueParse">
</div>

replace(control:any)
{
   this.valueParse=control.value.replace(/<(?!br|i|u)((\w+))>/gm,"&lt$1&gt")
   .replace(/<\/(?!br|i|u)((\w+))>/gm,'&lt\/$1&gt');
}

See stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM