Me and my friend are making a chat room for students at our school to use during free time and stuff. I am trying to add a filter so that it will remain SFW. I am very new to JavaScript so when I added the filter you couldn't send messages in the chat anymore. However when I make the filter script a comment and disable it, the messages send just fine.
Filter Code:
var array = array.js
message.replace(array, "****");
Messaging Code:
if (message && connected) {
$inputMessage.val("");
addChatMessage({
username: username,
message: message
});
socket.emit("new message", message);
}}
My friend is responsible for the Messaging code since he is much more experienced at JavaScript, but he is very busy and can't add it right now so I am trying to.
Assuming you have a array to filter which is array you could split your message by white space and then check each word to see if it contains a bad word.
Two methodologies (FYI neither is perfect. both of these solutions have plenty of edge cases/loopholes: I'd recommend a js package that has more thought put into it npm: bad-words, npm: censor-sensor, or npm: swearjar)
Both split the message message.split(' ') and then iterate over each word to see if it needs replacing .map. The first checks to see if the current word is in array and the second sees if array words contain the current word, then if so replace with ****
const array = ['badword', 'nsfw']
let message = 'my message is full of badwords which may be nsfw'
message = message.split(' ').map(word => array.includes(word.toLowerCase()) ? '*****' : word).join(' ')
console.log(message)
message = 'my message is full of badwords which may be nsfw'
message = message.split(' ').map(word => array.some(nsfword=>word.toLowerCase().includes(nsfword)) ? '*****' : word).join(' ')
console.log(message)