2015-07-02 47 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)