简体   繁体   中英

How To Use A Function To Edit String Data?

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?

  • 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, == password means "true if data.message is exactly equal to the value of the variable password ". If you want to see if the variable password is contained in the string, do data.message.contains(password)
const checkForMod = (data, username) => {
  if (data.message == password) {
    username.data += "Mod";
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM