Tân Nguyễn Tân Nguyễn - 18 days ago 5
AngularJS Question

How to display custom html tag?

I'm trying to read user input text and display it.

I've tried:

<div>
<input type="text" ng-model="post.content" />
</div>

<div>
<div ng-bind-html="post.content| htmlize"></div>
</div>


Script:

let app = angular.module('myApp', ['ngSanitize']);

app.controller('myController', function ($scope) {

// controller implements...

}).value('HTMLIZE_CONVERSIONS', [

{ expr: /\n+?/g, value: '<br />' },
{ expr: /\[([BUI])\](.+)\[\/\1\]/g, value: '<$1>$2</$1>' }

]).filter('htmlize', function (HTMLIZE_CONVERSIONS) {

return function (string) {
return HTMLIZE_CONVERSIONS.reduce(function (result, conversion) {
return result.replace(conversion.expr, conversion.value);
}, string || '');

};
});


When I type:


[B]bold[/B] [U]underline[/U] [I]italic[/I]


it would convert to:


bold u̲n̲d̲e̲r̲l̲i̲n̲e̲ italic


My question: how to prevent the code detects other html tags?

I've tried:

Case:


<script>alert('')</script>



Result:





Case:


<h1>text</h1>



Result:

text



My goal: I just only want to convert
[B][U][I]
to
<b><u><i>
and display them as html tags (as I show), ortherwise; display it as an plain text.

How can I do that?

Answer

You can

replace < with &lt;

replace > with &gt;

to display < and > in plain text and then replace [ and ] characters with < and > to make them correct HTML tags