Home > Back-end >  How to add hashtag and mention in textInput react-native
How to add hashtag and mention in textInput react-native

Time:03-01

I'm facing this challenge when client want me to add mention and hashtag to the textInput, will look like this

enter image description here

I tried some lib , but they are not give me the result like this, so i tried to make a custom one,, but i wonder how can we detect when we type "@" or "#", i struggle for days because of this, please help

CodePudding user response:

Regex is perfect for this:

inputStr.replace(/(?<=#).*?(?=( |$))/g, hashtag => {
    // do something with hashtag, e.g. "fenty"
    return hashtag;
});

Breaking the regex down:

(?<=#)       # match anything preceded by "#"
.*?          # match everything without greedy matching
(
  ?=         # match anything with the following after it:
  ( |$)      # space or end of text
)

g (global) means to match all occurrences.

The same thing can be done for @:

inputStr.replace(/(?<=@).*?(?=( |$))/g, mention => {
    // mention == "fenty"
    return mention;
});

You can also perform manipulations on, say, the hashtags to turn them into links or whatever:

const newString = inputStr.replace(/(?<=#).*?(?= )/g, hashtag => {
    // do something with hashtag, e.g. "fenty"
    return `<a href="/hashtags/${hashtag}">${hashtag}</a>`; // "stunna new year highlighter  <a href="/hashtags/fenty">fenty</a> @fenty"
});

Demo:

"hello #yes no #maybe so #ionter6 #000".replace(/(?<=#).*?(?=( |$))/g, hashtag => {
    console.log("Hashtag from post:", hashtag);
    return hashtag;
});

CodePudding user response:

I think you should give this library a try, I did the same using react-native-controlled-mentions

  • Related