1

My input is

const text = 'Hello @kevin12 How are you?'

How I render it

<span>{text}</span>

How I want to render it

<span>Hello <em>@kevin12</em> How are you?</span>

My parsing function (incomplete)

const parseText = value => {
  const mention = value.substring(value.lastIndexOf('@')+1)
  const words = value.split(mention)
  return words.map(word => word === mention ? React.createElement('em', {}, word) : word)
}

...

<span>{parseText(text)}</span>

Please help me complete this rendering function.

0

3 Answers 3

2
const parseText = value => {
    const words = value.split(' ')
    return words.map((word, index) => {
      if (index !== words.length - 1) {
        word += " "
      }
      return word[0] === '@' ? <em>{word}</em> : word;
    })
}
Sign up to request clarification or add additional context in comments.

Comments

1

Split by words, iterate over the array and find the item that start with @

export default function App() {
  const text = "Hello @kevin12 How are you?";
  const parseText = value => {
    const mention = value.split(" ");
    return mention.map(w => (w[0] === "@" ? <em> {w} </em> : <> {w}</>));
  };
  return (
    <span>
      <span>{parseText(text)}</span>
    </span>
  );
}

Comments

0

I will suggest going through the regex, here is the sample code

    const text = 'Hello @kevin12 How are you?';
    let finalResult = test;
    let re =/(?:^|\W)@(\w+)(?!\w)/g;
    let match,matches =[];
   while(match =re.exec(test)){
     let found ='@'+match[1];
     let replace ='<em>'+found+'</em>';
     finalresult =finalResult.replace(found,replace);
   }
 console.log(finalResult) ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.