我有一个文本和一些来自JSON对象的字符串:
links: [
{text: "Bharath Karunamurthy", type: "User", id: 4},
{text: "Raj Sanghvi", type: "User", id: 2}
]
text: "Bharath Karunamurthy follows Raj Sanghvi"
我想要做的是创建一个包含链接的新文本:
text_with_links: "<a href=/users/4 >Bharath Karunamurthy</a> follows <a href=/users/2 >Raj Sanghvi</a>"
我尝试了以下但是不起作用:
text = this.text
for element in this.links
text = text.replace /element.text/, "<a href='/users/"+element.id+"' >"+element.text+"</a>"
return text
答案 0 :(得分:1)
摆脱斜线。
text = text.replace element.text, "<a href='/users/"+element.id+"' >"+element.text+"</a>"
字符串替换方法适用于字符串和正则表达式。