Coffeescript - 替换字符串

时间:2014-11-28 22:00:04

标签: regex coffeescript

我有一个文本和一些来自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

1 个答案:

答案 0 :(得分:1)

摆脱斜线。

text = text.replace element.text, "<a href='/users/"+element.id+"' >"+element.text+"</a>"

字符串替换方法适用于字符串和正则表达式。