1

What is the best way to escape HTML in the input field? For example, I've search input field

<input id="search" type="text" ng-model="search" placeholder="search...">

And I want to escape if somebody types something like this:

<script>alert("test123");</script>
2
  • @Fran the question is clear. He wants to escape HTML characters. Commented Dec 6, 2017 at 9:32
  • 1
    @lin This Question does not show research effort and the requirements are not clear to me when OP wants to escape the characters. Hence I'm asking for more information. Commented Dec 6, 2017 at 9:33

3 Answers 3

3

this completely depends on your use case. If you just want it to escape it for the users view (so basically sanitizing) you can use angular $sanitize & $sce for it

https://docs.angularjs.org/api/ngSanitize/service/$sanitize and https://docs.angularjs.org/api/ng/service/$sce

however if you want to store it somewhere and want it escaped, you can build a filter. You can find an example here: Escape HTML text in an AngularJS directive

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

Comments

1

You could use lodash _.escape([string='']). This is a easy and simple solution.

_.escape($scope.search);

Comments

-1

You could use pattern for your input box like -

<input type='text' pattern='[a-zA-Z0-9]+'>

Use an expression that best suits your needs.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.