Home > Back-end >  How to wrap words with anchor tags in react if string contains certain symbols
How to wrap words with anchor tags in react if string contains certain symbols

Time:03-13

Hey guys am working on blog content with #hashtags and @mentions,i want a to check for all the words in a string if this words have @mention or #tags wrap them with anchor tags, so incase i have something like "hello @watchdog are you with @example and #trends #football"

so i want to wrap to have something like @watchdog @exmaple #exmaple

am using react js

export const text = (text) =>{
const [linktext,setLinkText] =  useState('')

useEffect(()=>{
},[])

return (
   <div>{text}</div>
)
}

CodePudding user response:

export const text = (text) =>{
const [linktext,setLinkText] =  useState("hello @watchdog are you with @example and #trends #football")

useEffect(()=>{
},[])

return (
   <div>{linktext.split(" ").map(word => (
         (word.includes("@") || word.includes("#"))
           ?
         <a>{word} </a>
        :
        <p>{word}</p>
    ))}</div>
)
}
  • Related