如何替换标签并保留其内容?

时间:2020-09-25 14:20:25

标签: javascript html

我有以下html代码:

<i>https://www.example.com/01.png</i>

我想用另一个标签替换i标签并保留相同的内容 例如。

<a><img src=" + my url + "></a>

我确实尝试过,但是没有用

var a = $ (this)، b = a.text (). trim ()، c = a.html ()؛ $ ("i") .replaceWith ('<a>' + c + "</a>")؛

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式提取i标签之间的URL,然后创建aimg元素,并将提取的URL字符串设置为src的值img元素上的属性。

const regex = /(https:[^<]+)/g;
const str = '<i>https://www.example.com/01.png</i>';

const matches = str.match(regex);
const result = `<a><img src="${matches[0]}"/></a>`;

console.log(result);

答案 1 :(得分:0)

您可以使用像这样的简单正则表达式:

document.body.innerHTML = document.body.innerHTML.replace('<i>', '<otherTag>');
相关问题