Keep ampersand character codes in HTML template

I have a table with the labels:

var labels = ['Hello user, start here', 'E&Y']; //etc

Labels are being concatenated in HTML like:

'<p>'+label[i]+'</p>'

So the effect is:

<p>Hello user, start here</p>

and browser shows text 'Hello user, start here'. It is a good behaviour, but I want to show labels also in another case as follows:

<p>Hello user&#44; start here</p>

so

'Hello user&#44; start here' without decoding.

How to get the desired effect?

EDIT:

I simplified this process to show us clearly what I meant:

var labels = ['Hello user&#44; start here', 'E&amp;Y'];
var label = $( "<p>"+labels[0]+"</p>");
$("body").append(label);

I can't modify the labels array.

2 answers

  • answered 2018-12-05 20:09 marzelin

    When you put the text directly into a text node it won't be decoded: document.createTextNode(labels[0])

    var labels = ['Hello user&#44; start here', 'E&amp;Y'];
    
    document.body.insertAdjacentHTML(
      "beforeend",
      '<p>'+labels[0]+'</p>'
    );
    
    document.body.appendChild(
      document.createTextNode(labels[0])
    );

  • answered 2018-12-05 20:11 Sk.

    do you try with ... safe html code... &amp; is showed as "&"

    var labels = ['Hello user&amp;#44; start here', 'E&amp;Y'];