Summary
If the "string" you need to convert is already part of the content of an HTML element, then here is a POV (plain old vanilla) JavaScript (i.e. non-jQuery) solution:
element.outerHTML = element.innerHTML;
Examples and Explanation
So, for example, if you wanted to unwrap/remove all spans in your document you could loop through all the relevant elements like the following:
document.querySelectorAll('span').forEach(spanElmt => {
spanElmt.outerHTML = spanElmt.innerHTML;
};
The following example demonstrates how this works, showing that the element specified is removed/unwrapped, while any elements nested inside remain intact.
const btn = document.querySelector('button');
const redSpan = document.querySelector('.red' );
const par = document.querySelector('p' );
const div = document.querySelector('div' );
const unwrapElmt = elmt => {
elmt.outerHTML = elmt.innerHTML; // *** the key line
};
const showParagraphHTML = () => {
div.textContent = 'HTML for the above line: ' + par.innerHTML;
};
showParagraphHTML();
const unwrapRedSpan = () => {
unwrapElmt(redSpan);
showParagraphHTML();
};
btn.addEventListener('click', unwrapRedSpan);
.red {
color: red;
}
.italic {
font-style: italic;
}
<button>Click here to unwrap/remove red span</button>
<p>Here is <span class="red">some <span class="italic">very</span> red</span> text.</p>
<p><div></div>
Inserting a String into an HTML Element
This solution requires that the text/string to be modified is already part of an HTML document or element. Thus, it won't work on a stand-alone string such as the following:
const myStr = 'some <span><i>very</i> interesting</span> thing';
myStr.outerHTML = myStr.innerHTML; // won't work
This is, ultimately, what the original question was asking. However, the string above can be made part of a temporary intermediate orphan HTML container element, after which this solution becomes useable:
const myStr = 'some <span><i>very</i> interesting</span> thing';
const container = document.createElement('div'); // a temporary orphan div
container.innerHTML = myStr;
const spanToUnwrap = container.querySelector('span');
spanToUnwrap.outerHTML = spanToUnwrap.innerHTML;
const myModifiedStr = container.innerHTML;
This might seem like overkill if, e.g., you only want to remove one or a few simple tags from a single string, as suggested in the question. In such a case, a regex-based replacement would probably suffice such as that proposed in another answer. However, for anything more complicated (e.g. only wanting to remove spans of a specific class, etc.), using a temporary orphan HTML element as an intermediate might be quite useful.
Note that the strategy described in this section is ultimately what a different answer is showing how to do with jQuery. However, if your initial string is already part of an HTML element, and you're not yet needing jQuery, using jQuery might be overkill when this outerHTML
/innerHTML
swap is really all you need.