1

So - I have a string in javascript liks so:

var foo = "Hello™";

I need to print this out in HTML (via JS) so it looks like this:

Hello™

Sounds easy, but I obviously am missing something cause I can't figure out a simple solution for it yet.

EDIT - here is more code:

var label = document.createElement('label');
var foo = selectData.options[i][1]; // this is "Hello&trade";

label.innerHTML = foo;

container.appendChild( label );
1
  • Where's the code? Commented Jan 30, 2018 at 19:26

2 Answers 2

3

Just append it into the innerHTML property. innerHTML will html encode the given input and that append it to the node.

var foo = "Hello™";

document.getElementById('label').innerHTML = foo;
<label id="label"></label>

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

5 Comments

Don't you think this is a comment rather than an answer?
Have you checked the example
That doesn't appear to work. var foo = "Hello&Trade;"; var label = document.createElement('label'); label.innerHTML = foo; results in the label being "Hello&Trade";
I posted some more code showing some more context to my issue
I found the bug, the issue was that I was getting passed &Trade and not &trade - so the symbol could not convert properly. The above is the correct answer, I just couldn't see it
0

First separate the '&trade' and check for it in an if-statement and then give var the value of the hexcode equivalent which is 'u2122' then the rest of the code should do the work.

String.prototype.hexEncode = function(){
    var hex, i;
    var result = "";

    for (i=0; i<this.length; i++) {
        hex = this.charCodeAt(i).toString(16);
        result += ("000"+hex).slice(-4);
        }

    return result
}

    String.prototype.hexDecode = function(){
        var j;
        var hexes = this.match(/.{1,4}/g) || [];
        var back = "";

         for(j = 0; j<hexes.length; j++) {
              back += String.fromCharCode(parseInt(hexes[j], 16));
        }

    return back;
}

var str = "\u2122"; 
var newStr = (str.hexEncode().hexDecode());
var foo = "Hello" + newStr;
console.log(foo);

Comments

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.