我正在使用 React 和外部 API
我正在从一个带有网址的外部 api 接收数据, 即
sampleText = Ethereum’s original token distribution event, managed by the [Ethereum Foundation](https://messari.io/asset/ethereum)
我想使用以下方法将网址转换为链接:
const turnIntoLink =(text)=>{
const urlFilter = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
return text.replace(urlFilter, (url)=>{
return '<a href="' + url + '">' + url + "</a>";
})
}
turnIntoLink(sampleText)
当我使用上面的代码时,它会正确读取网址但返回
... managed by the [Ethereum Foundation](<a href="https://messari.io/asset/ethereum">https://messari.io/asset/ethereum</a>)
当我把 turnIntoLink 改成这个时
const turnIntoLink =(text)=>{
const urlFilter = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
return text.replace(urlFilter, (url)=>{
return <a href={url}>${url}</a>;
})
}
它回来了
... managed by the [Ethereum Foundation]([object Object])
更新 CoinDetail.jsx 以反映反向引用的使用
import React from "react";
const CoinDetail = (props) => {
const { profile } = props.details;
const turnIntoLink = (text) => {
const urlFilter = /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi;
return text.replace(urlFilter, '<a href="$2">$1</a>');
};
const display = () => {
return (
<div>
<div>
Launch Details:
{turnIntoLink(profile.economics.launch.general.launch_details)}
</div>
</div>
);
};
return <section>{profile ? display() : "Loading"}</section>;
};
export default CoinDetail;
我怎样才能让它返回一个实际的 a 元素?
更新:
通过在下面的返回中执行此操作,我能够使其正常工作
<span
dangerouslySetInnerHTML={{
__html: turnIntoLink(
profile.economics.launch.general.launch_details
),
}}
></span>
它有效,但我觉得这有点hacky,有更好的方法来做到这一点。有吗?
答案 0 :(得分:2)
在 React 中,您可以将以下代码与 React String Replace 一起使用:
return (
<div>
{reactStringReplace(content, /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi, (match, x, y) => ( <a href={y}>{x}</a> ))}
</div>
如果您使用纯 JavaScript,则可以使用
const turnIntoLink = (text) => {
const urlFilter = /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi;
return text.replace(urlFilter, '<a href="$2">$1</a>');
}
参见regex demo。 详情:
\[
- [
字符([^\][]*)
- 第 1 组:除 ]
和 [
之外的任何零个或多个字符]\(
- ](
字符串((?:https?|ftps?|file):\/\/[^()]*)
- 第 2 组:http
、https
、ftp
、ftps
、file
然后是 ://
子字符串然后是除 (
和 )
\)
- 一个 )
字符。查看 JavaScript 演示:
const turnIntoLink = (text) => {
const urlFilter = /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi;
return text.replace(urlFilter, '<a href="$2">$1</a>');
}
console.log( turnIntoLink("Ethereum’s original token distribution event, managed by the [Ethereum Foundation](https://messari.io/asset/ethereum)") );