class ChatApp { constructor() { this.keywordRegex = /hello|hi|hey/g; } receiveMessage(message) { if (this.keywordRegex.test(message)) { this.sendGreeting(); } } sendGreeting() { console.log("ChatApp: Hello, how can I assist you today?"); } } let chatApp = new ChatApp(); chatApp.receiveMessage("hi, how are you?"); chatApp.receiveMessage("hello, can you help me?");
chatApp.receiveMessage("hi, how are you?"); // "ChatApp: Hello, how can I assist you today?" chatApp.receiveMessage("hello, can you help me?"); // Logs nothing
In JavaScript, RegExp objects with the g (global) flag retain state between matches due to the lastIndex property, which can lead to unexpected results when reused across different inputs.
The solution is to create a fresh RegExp object for each incoming message, ensuring proper recognition and response to all greetings.
class ChatApp { receiveMessage(message) { let keywordRegex = /hello|hi|hey/g; if (keywordRegex.test(message)) { this.sendGreeting(); } } sendGreeting() { console.log("ChatApp: Hello, how can I assist you today?"); } } let chatApp = new ChatApp(); chatApp.receiveMessage("hi, how are you?"); // "ChatApp: Hello, how can I assist you today?" chatApp.receiveMessage("hello, can you help me?"); // "ChatApp: Hello, how can I assist you today?"