userMod2
userMod2

Reputation: 8960

Angular - Strip all tags from inputs

In my Angular app, I want to sanitise any inputs to strip any/all tags, so even if a user entered <h1>superman</h1> the html tags would be stripped.

Now I've read about ngSanitize however on this docs page https://docs.angularjs.org/api/ngSanitize/service/$sanitize it mentions whitelist, so I presume that means Angular would accept things like <h1>.

Is my understanding in this correct?

And if so, how do i forcefully remove any and all tags from any input?

Thanks.

Upvotes: 2

Views: 1334

Answers (2)

S4beR
S4beR

Reputation: 1847

please refer to this plnkr example https://plnkr.co/edit/F9K3sekUQUJPBUts8Jdw?p=preview

var strip = function() {
   var tmp = document.createElement("DIV");
   tmp.innerHTML = $scope.strip; // assuming text box is using "strip" for ng-model
   return tmp.textContent || tmp.innerText || "";
};

It can be done with simple Javascript. No need for ngSanitize or any other angularjs specific code.

Upvotes: 0

rgvassar
rgvassar

Reputation: 5811

ngSanitize simply makes html safe, so it can't run javascript inside. You'd probably want to use the simple javascript replace method with a regex here.

something like:

var str = '<h1>superman</h1>';
str.replace(/<[^>]+>/g, '');

This would remove any XML tags, not just html.

Upvotes: 5

Related Questions