我的输入是
const text = 'Hello @kevin12 How are you?'
如何渲染
<span>{text}</span>
如何渲染
<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>
请帮我完成这个渲染功能。
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;
})
}
按单词拆分,遍历数组并查找以@
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>
);
}
我建议通过正则表达式,这里是示例代码
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) ;