简体   繁体   English

Javascript替换文字无法呈现HTML

[英]Javascript replace text doesn't render HTML

With

<div>[[foo]] bar</div>

I run 我跑

replace(/\[\[(.*)\]\]/, function(t){return "<a href='"+t+"'>"+t+"</a>"});

and the page text just changes to the literal 然后页面文本变为文字

<a href='[[foo]]'>[[foo]]</a> bar

instead of creating a working hyperlink. 而不是创建有效的超链接。

So the question is, how can I get working html using the replace method instead of seeing a literal? 所以问题是,我怎么能使用replace方法而不是看到文字来工作html? Please do not recommend that I just use a linkify library -- this is just an example. 请不要建议我只使用linkify库-这只是一个示例。

I don't know why nnnnnn didn't post his comment as an answer, because it is correct. 我不知道为什么nnnnnn没有发表他的评论作为答案,因为它是正确的。 The function in replace accepts the matched substring as the first parameter and every other argument is "nth parenthesized submatch string" as described in the MDN docs . replace的函数接受匹配的子字符串作为第一个参数,其他每个参数都是“第n个带括号的子匹配字符串”,如MDN docs中所述

Here is the code: 这是代码:

"<div>[[foo]] bar</div>".replace(/\[\[(.*)\]\]/, function(m, t){return "<a href='"+t+"'>"+t+"</a>"})
"<div><a href='foo'>foo</a> bar</div>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM