Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - How to check if someone is mentioned after @ typed in message

I have a chat application, and as a user is typing a message, I want to know if they mention someone by checking the characters directly after the @, and send them a notification.

Step 1 is to actually make sure the character typed is @:

onTextChange = (message) => {
    const lastChar = this.state.messageText.substr(this.state.messageText.length - 1)
    const currentChar = message.substr(message.length - 1)
    const spaceCheck = /[^@A-Za-z_]/g
    this.setState({
        messageText: message
      })

    //Empty message, do nothing
    if(message.length === 0) {
        console.log("message length 0")
    } 
    
    //Non Empty Message
    else {

      //No @ detected
      if (spaceCheck.test(lastChar) && currentChar != '@') {
        console.log("normal text")
      } 
      
      //@ Detected
      else {

        
        const checkSpecialChar = currentChar.match(/[^@]/)
        //Make sure it is @
        if (checkSpecialChar === null || currentChar === '@') {

             console.log('last char @')

            //Extract the characters following the @ and see if they are a username
            //I can save in state, but what if multiple people are mentioned??

        } else if (checkSpecialChar != null) {
            console.log("no @")
        }

      }

    }

}

Now that I have that, how can I add some logic where I check the letters following the message to see if they form an existing username? I can save in state, but what if multiple people are mentioned?

TIA

question from:https://stackoverflow.com/questions/65934156/how-to-check-if-someone-is-mentioned-after-typed-in-message

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You shouldn't only check for @ but for some additional rules to be sure, that it's not a email-address or something else.

Maybe something like this regex: s@([A-Za-z1-9!#?.:~]{2,})s* This catch the username if:

  • start with whitespace
  • second character @
  • then username can be characters, numbers and gilen special-characters
  • must at least have a username length of 2 or more
  • must followed by an whitespace

With that, and if you use global (/g) as regex-option, you should get all your user-names within an result-array.

Then you can check this Array against your user-database if they exist (or not).

Hope this helps you a bit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...