none
none

Reputation: 21

How to replace tag and leave its content?

I have the following html code :

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

I want to replace the i tag with another tag and leave the same content eg.

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

I did try, but it didn't work

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

Upvotes: 1

Views: 98

Answers (2)

Yousaf
Yousaf

Reputation: 29282

You could extract the URL between i tags using a regular expression and then create a and img element and set the extracted URL string as a value of the src attribute on the img element.

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);

Upvotes: 1

marcdecline
marcdecline

Reputation: 186

You can use a simple regular expression like this :

document.body.innerHTML = document.body.innerHTML.replace('<i>', '<otherTag>');

Upvotes: 0

Related Questions