How do I check equality between `'` and '?

Viewed 56

I'm quite new to web dev and am giving my very first steps in AJAX functions and HTTP requests.

I only know vanilla JS, CSS and HTML. I also know very very little about regExps so would really appreciate if answers could respect this.

I'm developing a simple quiz game where I fetch Q&As from opentdb. The data is saved in an array of questions with the following format (notice the ' on correct-answer):

[..., {
category: "Entertainment: Film",
type: "multiple",
difficulty: "medium",
question: "What Queen song plays during the final fight scene of the film "Hardcore Henry"?",
correct_answer: "Don't Stop Me Now",
incorrect_answers: [
"Brighton Rock",
"Another Bites the Dust",
"We Will Rock You"
]
}, ...]

After having successfully fetched the data the first thing I do is to put all the correct answers in an array which I use later to compare with the user's selected answer. My array of correct answers, in this example would be something like (again notice the '):

[... ,"Don't Stop Me Now", ...]

When I render the questions and answers to the DOM, by creating the necessary elements and using innerHTML everything shows up well on the browser (i.e. instead of ' I get the actual '.

However, later, when I'm collecting the user's selected answer with:

const selectedAnswer = event.currentTarget.innerHTML

I get "Don't Stop Me Now" and when I compare this with my array of correct answers, I get something like:

"Don't Stop Me Now" === "Don't Stop Me Now"

which returns false when, in fact should be true because is the correct answer...

How do I solve this?

3 Answers

Well ' is a HTML Entity. So I create a new element, then set its innerHTML property to the text with the HTML entity then compare it's innerText with the user's input.

const text = "Don't Stop Me Now";
const checkAnswer = (correct, input) => Object.assign(document.createElement('span'), { innerHTML: correct }).innerText == input;
console.log(checkAnswer(text, "Don't Stop Me Now"));

' is HTML Entity code for '. so if this only what you concern, you could try to map that array first and replace/convert that HTML Entity code into character, like this:

[... ,"Don't Stop Me Now", ...].map(item => item.replace(/'/g, "'"));

You could try using backticks instead of the HTML code for '.

[... ,`Don't Stop Me Now`, ...]
Related