我正在使用React和外部API
我正在接收来自外部api的数据,该api具有整个url,例如
sampleText = Ethereum’s original token distribution event, managed by the [Ethereum Foundation](https://messari.io/asset/ethereum)
我想把url变成链接使用:
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)
当我使用上面的代码时,它正确地读取url,但返回
... managed by the [Ethereum Foundation](<a href="https://messari.io/asset/ethereum">https://messari.io/asset/ethereum</a>)
当我把turnIntoLink改成this
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>
它工作,但我觉得这是有点黑客,有一个更好的方法来做到这一点。是吗?
InReact,您可以使用以下代码与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演示。细节:
[
- a[
char([^][]*)
-第1组:除]
和[
以外的任何零或多个字符](
-](
string((?:https?|ftps?|file)://[^()]*)
-组2:http
,https
,ftp
,ftps
,file
然后是://
子字符串,然后是除(
和)
以外的任何零或多个字符)
- a)
char.
查看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)") );