下面是我的代码。
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 代码。如何从字符串转换标签?
最佳答案
创建一个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)
关于JavaScript regexr 用html替换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31187144/