JavaScript regexr 用html替换字符串?

标签 javascript regex

下面是我的代码。

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/

相关文章:

javascript - TypeError : util. promisify 不是函数?

javascript - 如何对定义为字符串的变量执行 forEach 循环 |数组<字符串>?

javascript - IE : Problem with local content and Flash

regex - 我如何在没有某些足够的情况下进行正则表达式?

java - 如何在java中使用正则表达式解析给定的字符串

c++ - 使用 regex.h 时内存泄漏?

javascript - 添加了事件监听器,但需要点击 2 次

javascript - 如何从异步调用返回响应?

javascript - 广泛支持的正则表达式查看后面

excel - 从 VBA 中的范围中删除特殊字符