2015-07-02 51 views
0

以下是我的代码。JavaScript regexr用html替换字符串?

var input = "this is @renish profile"; 
var matches = input.replace(/(@\w*)/g,'<a href="http://example.com/users/profile/$1">$1</a>'); 

的输出是:

this is <a href="http://example.com/users/profile/@renish">@renish</a> profile 

这是打印HTML代码。如何从字符串转换标签?

+0

你到底想达到什么目的? – gipadm

+0

如果您使用的是jQuery,您可以使用jQuery.parseHTML()http://api.jquery.com/jquery.parsehtml/ –

+2

您现在如何将该字符串添加到页面中......这是$ 1,000的问题。 – epascarello

回答

2

创建一个div,并使用innerHTML。

var input = "this is @renish profile"; 
 
var matches = input.replace(/(@\w*)/g,'<a href="http://example.com/users/profile/$1">$1</a>'); 
 

 
var div = document.createElement('div'); 
 
div.innerHTML = matches; 
 

 
document.body.appendChild(div)