如何改变这个:
{dataFormat: 'hello my [friend=https://en.wikipedia.org/wiki/Friendship]'}
到此:
<div>
hello my <a onClick={...} href="https://en.wikipedia.org/wiki/Friendship">friend</a>
</div>
我需要能够以某种方式扫描字符串并动态创建链接。有什么想法吗?
dataFormat可以包含多个链接,其中包含未知顺序的&#34;常规&#34;文字和链接。
答案 0 :(得分:0)
使用完成此任务的正则表达式结束。
JSBin:https://jsbin.com/yogepa/edit?js,output
<强>代码:强>
renderSpan(content) {
return <span>
{content}
</span>
}
renderLink(content) {
const parts = content
.replace(/\[|\]/g, '')
.split('=');
return <a style={ styles.link } onClick={ alert }>
{parts[0]}
</a>
}
renderFormat() {
let { dataFormat } = this.state;
const regex = /(\[[^\]]+])*([^\[]+)(\[[^\]]+])*(\[[^\]]+])*([^\[]+)(\[[^\]]+])*(\[[^\]]+])*([^\[]+)(\[[^\]]+])*/;
const matches = regex.exec(dataFormat);
return matches.reduce((output, match, index) => {
if (match && index >= 2) {
output.push(match.indexOf('[') >= 0 ?
this.renderLink(match) :
this.renderSpan(match)
);
}
return output;
}, []);
}
我可能会改进正则表达式。