如何将句子中的某些单词转换为链接?
这是使用 React 在字符串中创建链接的示例。我发现的大多数例子都是我操纵 dom 的,所以经过一番折腾后,我想出了如何做到这一点。
function profile() {
const hashtagRegex = /\B(\#[a-zA-Z]+\b)(?!;)/gm;
const { fullName, userName, image, bio } = userProfileData;
const bioMatch = bio && bio.match(hashtagRegex);
const editbio = bio && bio.split(" ");
bioMatch &&
editbio.map((word, index) => {
if (word.match(hashtagRegex)) {
editbio[index - 1] = editbio[index - 1] + " ";
editbio[index] = <a href="https://google.com">{word}</a>;
} else {
editbio[index] = " " + word;
}
});
return (
<div className="profile">{editbio}</div>
);
}
如果您直接向数组索引添加空格,它会将链接转换为 [object][object]
,如果您尝试加入返回,它也会执行相同的操作,因此这对我有用。如果有人有更好的方法,请分享。
This is an example of creating links in a string using react. Most of the examples I found were my manipulating dom so after so messing around I figured out how to do it.
function profile() {
const hashtagRegex = /\B(\#[a-zA-Z]+\b)(?!;)/gm;
const { fullName, userName, image, bio } = userProfileData;
const bioMatch = bio && bio.match(hashtagRegex);
const editbio = bio && bio.split(" ");
bioMatch &&
editbio.map((word, index) => {
if (word.match(hashtagRegex)) {
editbio[index - 1] = editbio[index - 1] + " ";
editbio[index] = <a href="https://google.com">{word}</a>;
} else {
editbio[index] = " " + word;
}
});
return (
<div className="profile">{editbio}</div>
);
}
If you add spacing directly to the array index it converts the link into [object][object]
and if you try to join in the return it does the same so this worked for me. If someone has a better way to do it, please share.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您尝试使用 HTML 将网站链接到文本,最简单的方法是
The easiest way to link the website to the text if you are trying to do it with HTML would be