Forum Discussion
Check Key words in a text entry with JavaScript
Hello Guys! I,m Guio!
I was trying to make a texty entry quiz and my goal was to check if the answer is corret by checking if they used some key words.
I found this guy on youtube (https://youtu.be/R4SLR6UB-44) that used JavaScript to do that in three diferent ways, I was abble to make only the firt one work, can someone help please?
this is my code fore de second method:
var answer = getVar("TextEntry2");
var words = ["cat", "dog"];
var containsWords = words.every(word => new RegExp('\\b${word}\\b', 'i').test(answer));
setVar("key_words1", containsWords);
Copy and paste the code below exactly as it is:
var answer = getVar("TextEntry2"); var words = ["cat", "dog"]; var containsWords = words.every(word => new RegExp(`\\b${word}\\b`,'i').test(answer)); setVar("key_words1",containsWords);Issue: ${word} doesn’t interpolate inside quotes, so the regex looks for the literal text ${word} instead of the actual word.
Fix: Use backticks (template literals) so word is injected correctly.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
2 Replies
- NedimCommunity Member
Copy and paste the code below exactly as it is:
var answer = getVar("TextEntry2"); var words = ["cat", "dog"]; var containsWords = words.every(word => new RegExp(`\\b${word}\\b`,'i').test(answer)); setVar("key_words1",containsWords);Issue: ${word} doesn’t interpolate inside quotes, so the regex looks for the literal text ${word} instead of the actual word.
Fix: Use backticks (template literals) so word is injected correctly.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
- guilherme_pCommunity Member
It worked!
Thank you so much! 😁
Related Content
- 5 days ago
- 11 months ago