我是 React js 新手。我应该在我的项目中实现以下目标:
- 在大字符串中查找已定义的字符串
- 如果在大字符串中找到定义的链接,则使其可点击
我的代码:
function FindWord() {
const givenWord = "hello there click this Forgot password if you do not remember your password"
const toSearch="Forgot password"
return (
<>
{givenWord.includes(toSearch)?
givenWord.substring(0,givenWord.indexOf(toSearch).toString()) + `<span style={{color:'red'}}>${toSearch}</span>` + (toSearch)
:"No"}
</>
)
}
有更好的方法吗?
最佳答案
您必须使用 anchor 标记将搜索字符串括起来,如下所示:
const toSearch="Forgot password"
const target = givenWord.indexOf(toSearch);
const firstPart = givenWord.substring(0,target);
const secondPart = givenWord.substring(target + toSearch.length, givenWord.length)
return (
<>
{givenWord.includes(toSearch)?
<span>{firstPart}<a href="your-url.com" style={{color:'red'}}>${toSearch}</a>{secondPart}<span/>
:"No"}
</>
)
}
关于javascript - React.js : Find a string in a string and make it clickable if found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71550116/