【发布时间】:2020-03-23 00:20:36
【问题描述】:
假设我有一个这样的字符串:
Hello World, here are the links to {my Twitter: https://twitter.com/twitter} and to {Google: https://google.com}
我正在尝试编写一个用 html 元素替换 {Title: url} 的函数,以返回:
Hello world, here are the links to <a href="twitter.com/twitter">my Twitter</a> and to <a href="https://google.com>Google</a>
到目前为止我想出的是
function processWithRegex(string) {
let links = []
let regex = /[^{\}]+(?=})/g
let matches = string.match(regex)
matches.forEach((match) => {
match = match.split(': ')
links.push(match)
})
links.forEach((link) => {
html = `<a href='${link[1]}'>${link[0]}</a>`
console.log(html)
})
return string
}
显然,它返回输入字符串,但至少 console.logs 正确的 html 元素。我的大脑正在放弃,我真的很感激一些帮助......提前谢谢!
【问题讨论】:
标签: javascript regex logic