Lee
Lee

Reputation: 31040

js conditional test for utf string of special character

Say I have a div with innerHTML set using the HTML code for a rocket: 🚀

How do I do a conditional test for that character in javascript?

E.g. how do I get below to log "rocket"

let rocket = document.getElementById("rocket")

if (rocket.innerHTML == "🚀") console.log("rocket") 
else console.log("no rocket");
<div id="rocket">
&#128640;
<div>

Upvotes: 0

Views: 134

Answers (2)

user8426192
user8426192

Reputation: 61

I could achieve this way. Note that I've used ".innerText"

var ic = '🚀';
var r = document.getElementById("rocket");

if (r.innerText == ic) console.log("rocket"); 
else console.log("no rocket");
<div id="rocket">
&#128640;
</div>

Upvotes: 1

Hisham Bawa
Hisham Bawa

Reputation: 438

I tried using charCodeAt(0) to get the unicode character code of the rocket and got 55357 as the result and the code below works.

let rocket = document.getElementById("rocket").innerText

if (rocket.charCodeAt(0) == 55357) console.log("rocket") 
else console.log("no rocket");
<div id="rocket">
&#128640;
</div>

Hope this helps until a better answer comes. You can use console.log() to check the character code if you want to have a different item instead of a rocket.

Upvotes: 1

Related Questions