How to use handlebarsjs to convert extra characters (entity) in html attributes

 

For example, if you have a problem with symbols in your variable, and the data came from the server (such as this 'Men's'), you can follow a simple recommendation from the documentation and use {{{}}} for variable. But when you need to do something similar in html attributes, you will have a problem. This problem can be fixed using this example:

<div>
<div>{{rawName}}</div>
<img title="{{rawName}}" src="./mens.img">
</div>


<script>
let rawName = 'Men&amp;#x27;s'

Handlebars.registerHelper("prepareName", function(rawName) {
  let parser = new DOMParser
  let dom = parser.parseFromString(
      '<!doctype html><body>' + rawName,
      'text/html');
  let decodedString = dom.body.textContent
  
  return decodedString
})

</script>

Comments