2

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Cool - makes sense. So why doesnt Angular offer something like this out of the box as well? Isn't it important for things like username input fields where one would never really expect html to be entered?
They just can't implement everything a user might want to do. That's why they have filters. You can implement your own custom filter that can do this if you want.
0

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.

1 Comment

Thanks - I can see how this works, however will go for the above, easier for me to read :-). Thanks again, appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.