I'm facing this challenge when client want me to add mention and hashtag to the textInput, will look like this
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
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; });
I think you should give this library a try, I did the same using react-native-controlled-mentions
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.