Note: I am very new to Javascript.
I am trying to make a system in my chatroom where if you type a certain word (password) into the chat it will edit their username to include a special mod tag. I am doing this because we don't have profile systems and it is the best solution I could come up with. However I ran into a problem, I don't know how to edit a string's data (in this case the username) to add something to it with a function. If anybody could help it would be much appreciated.
Code:
if(data.message = password) {
username.data "Mod"
}
Extra question: In the above example, would having if(data.message = password) make it so that if it contains the variable (password) it would change it, or would it just be if they typed "password" that it would change it?
CodePudding user response:
- Single
=means assignment,==and===are equality comparasins (look up the difference) - To append to the end of a string, do
= - To answer your final question,
== passwordmeans "true ifdata.messageis exactly equal to the value of the variablepassword". If you want to see if the variablepasswordis contained in the string, dodata.message.contains(password)
const checkForMod = (data, username) => {
if (data.message == password) {
username.data = "Mod";
}
}
CodePudding user response:
You need to assign the new value back to the variable like this:
if(data.message == password) {
username.data = username.data "Mod";
// or using template string
username.data = `${username.data}Mod`;
}
I assumed username is an JSON object.
Answer to extra:
You need to use == (just the value) or === (strictly check the data type and value) in if condition. If the data.message is exactly the value of password then the condition is satisfied.
If you want to check if the password is a substring (the message contains value of password anywhere in the message) then you need to use String.prototype.includes. demo below:
if(data.message.includes(password)) {
username.data = username.data "Mod";
// or using template string
username.data = `${username.data}Mod`;
}
If you have more doubts, you can comment below. I'll update this answer.
Edit:
After reading your comment, I'm adding below sample to show you how above code works:
/*
Author: chankruze ([email protected])
Created: Mon Jan 31 2022 12:46:44 GMT 0530 (India Standard Time)
Copyright (c) geekofia 2022 and beyond
*/
const password = "qwerty1234"
const data = {
message1: `this is my ${password}`,
message2: password,
}
const username = {
data: "chankruze",
}
console.log(username.data);
if (data.message1.includes(password)) {
console.log("password found in side data");
username.data = "mod";
}
console.log(username.data);
if (data.message2 === password) {
console.log("exact match");
username.data = `${username.data}mod`;
}
console.log(username.data);
